gpt4 book ai didi

java - Android MediaPlayer 不会通过单击另一个按钮而停止

转载 作者:行者123 更新时间:2023-12-01 11:33:59 25 4
gpt4 key购买 nike

当您单击两个按钮时,您会听到两种声音。如何停止第一个声音并播放第二个声音,或者当我播放第一个声音时,第二个声音停止?我怎样才能创建这个?这是我的媒体播放器

final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
JSONArray songs = (JSONArray) response.getJSONArray("songs");
for ( int i = 0; i < songs.length(); i++)
{
// Create LinearLayout
audio = songs.getJSONObject(i).getString(TAG_AUDIO) ;
String chanson = songs.getJSONObject(i).getString("title") ;
String duration = songs.getJSONObject(i).getString(TAG_DURATION) ;

LinearLayout ll = new LinearLayout(getApplicationContext());
ll.setOrientation(LinearLayout.HORIZONTAL);

final TextView txtchanson = new TextView(getApplicationContext());
txtchanson.setText(chanson);
txtchanson.setPadding(10, 0, 10, 0);
TextView txtduration = new TextView(getApplicationContext());
txtduration.setText(duration);

final Button btn = new Button(getApplicationContext());
final MediaPlayer mp = new MediaPlayer();
mp.setAudioSessionId(i+1);

mp.setDataSource(audio);
mp.prepare();

btn.setId(i+1);
btn.setTypeface(ionicons);
btn.setText(getString(R.string.play_str));
btn.setLayoutParams(params);

final int index = i;
mp.setOnCompletionListener(new OnCompletionListener()
{

public void onCompletion(MediaPlayer mp)
{

btn.setText(getString(R.string.play_str));
}
});

btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{


Log.i("TAG", "index :" + index);
Toast.makeText(getApplicationContext(),
"Clicked Button Index :" + btn.getId(),
Toast.LENGTH_LONG).show();
boolean b = false ;
if ( b == false )

{

//txtchanson.setTextColor(R.color.green);
mp.start();
btn.setText(getString(R.string.pause_str));
b = true;

}

else //if (btn.getText().equals( getString(R.string.pause_str)))
{
mp.pause();
btn.setText(getString(R.string.play_str));
//txtchanson.setTextColor(R.color.gray);
b = false;

}
/* else if (b == true )
{
btn.setText(getString(R.string.play_str));
mp.pause();
}*/
}
});


ll.addView(btn);
ll.addView(txtchanson);
ll.addView(txtduration);

lm.addView(ll);

}

最佳答案

您应该将 boolean b = false ; 行放在 onClick 方法之外,它应该作为全局变量,因为每次单击时,当您转到 onClick 方法时,您的 b 变量得到一个假值,并且它永远不会进入 if-else 语句的 else 子句。其他都还好。

关于java - Android MediaPlayer 不会通过单击另一个按钮而停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com