我是编程的新手,在引用google的开发网站时,我想出了一个简单的媒体播放器来播放用户选择的文件。在第一次选择要播放的文件时,应用程序似乎运行正常,但在第二次选择文件后立即崩溃。我已粘贴下面的代码。任何帮助将不胜感激。
public class MainActivity extends Activity {
private static int Reqs =1;
private String a;
MediaPlayer md=new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Start = (Button) findViewById(R.id.button);
final Button Stop = (Button) findViewById(R.id.button3);
final Button Pause = (Button) findViewById(R.id.button2);
final Button Select = (Button) findViewById(R.id.button4);
Pause.setEnabled(false);
Stop.setEnabled(false);
Start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
md.start();
Toast.makeText(getApplicationContext(), "Playing", Toast.LENGTH_SHORT).show();
Pause.setEnabled(true);
Stop.setEnabled(true);
}
});
Stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Pause.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stopped", Toast.LENGTH_SHORT).show();
md.stop();
}
});
Pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
md.pause();
Toast.makeText(getApplicationContext(), "Paused", Toast.LENGTH_SHORT).show();
}
});
Select.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/mpeg");
startActivityForResult(Intent.createChooser(intent, "Choose"), Reqs);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode <= Reqs && resultCode ==-1) {
Uri videoUri = data.getData();
a = videoUri.toString();
md.setDataSource(a); //try-catch surrounding it
md.prepare(); //try-catch surrounding it
}
}
}
答案 0 :(得分:0)
您没有调用reset()
来重置MediaPlayer
对象的状态。
正如Android的文档所述:
为了重用处于错误状态的MediaPlayer对象并从错误中恢复,可以调用reset()将对象恢复到其空闲状态。
请查看:https://developer.android.com/reference/android/media/MediaPlayer.html