我创建了一个带有三个按钮的应用程序,用于播放,暂停和停止。当我单击按钮停止然后单击播放它不播放任何内容。我该怎么办?
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
public class Main2Activity extends AppCompatActivity {
Button button1,button2,button3;
MediaPlayer mpUkulele, mpDrums;
// int playing;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button1 = (Button) findViewById(R.id.btnPlay);
button2 = (Button) findViewById(R.id.btnPause);
button3 = (Button) findViewById(R.id.btnStop);
button1.setOnClickListener(bPlay);
button2.setOnClickListener(bPause);
button3.setOnClickListener(bStop);
mpUkulele = new MediaPlayer();
mpUkulele = MediaPlayer.create(this,R.raw.ukulele);
mpDrums = new MediaPlayer();
mpDrums = MediaPlayer.create(this,R.raw.drums);
// playing = 0;
}
Button.OnClickListener bPlay = new Button.OnClickListener() {
@Override
public void onClick(View v) {
final Spinner spinner=(Spinner) findViewById(R.id.Songs);
int pos=spinner.getSelectedItemPosition();
switch (pos)
{
case 0:
mpDrums.start();
break;
case 1:
mpUkulele.start();
break;
}
}
};
Button.OnClickListener bPause = new Button.OnClickListener() {
@Override
public void onClick(View v) {
final Spinner spinner2=(Spinner) findViewById(R.id.Songs);
int pos2=spinner2.getSelectedItemPosition();
switch (pos2)
{
case 0:
mpDrums.pause();
break;
case 1:
mpUkulele.pause();
break;
}
}
};
Button.OnClickListener bStop= new Button.OnClickListener() {
@Override
public void onClick(View v) {
final Spinner spinner3=(Spinner) findViewById(R.id.Songs);
int pos3=spinner3.getSelectedItemPosition();
switch (pos3)
{
case 0:
mpDrums.stop();
mpDrums.reset();
break;
case 1:
mpUkulele.stop();
mpUkulele.reset();
break;
}
}
};
}
我能够流式传输音频并且没有任何问题地停止它,但是当我尝试在停止后再次启动它时,它无法启动,我无法再次播放音乐。希望有这个问题的解决方案
答案 0 :(得分:0)
您必须准备 MediaPlayer才能再次播放。所以基本上将此代码添加到您拥有的每个媒体播放器中。
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
prepare();
}
});
public void prepare() {
if (mediaPlayer!= null) {
mediaPlayer.prepare();
}
}