我有一个MediaPlayer
对象和一个微调器,所有歌曲都位于 SD 卡上。我正在尝试创建每个播放、暂停、停止、上一个和下一个按钮的代码。
When an item from the spinner is being selected, i'm getting the MediaPlayer from it, and set its data source and calling prepare method. 这是代码:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Context context = getApplicationContext();
CharSequence text = "onItemSelected";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(sdcard_playlist.get(arg2));
applyValuesToEqualizer();
mediaPlayer.prepare();
index = arg2;
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
这是每个停止和下一步按钮的代码:
public void stopSong(View view) {
if (isPlaying) {
mediaPlayer.reset();
isPlaying = false;
spinner.setSelection(index, false); // index is the index of the chosen item from spinner
seekbar.setProgress(0);
}
}
public void nextSong(View view) {
if (isPlaying) {
mediaPlayer.reset();
isPlaying = false;
spinner.setSelection(index + 1, false);
seekbar.setProgress(0);
playPauseSong(findViewById(R.id.pause_music_button));
} else {
spinner.setSelection(index + 1, false);
seekbar.setProgress(0);
}
}
发生的事情是,当调用 nextSong() 时,一切正常,并且显示了 onItemSelected() 中的 toast,但是当调用 stopSong() 时,没有执行 onItemSelected() 并且未显示 toast,这首歌正在停止,但是当我再次单击播放按钮时,出现异常:在状态 1 中调用开始,错误 (-38, 0),这是因为 mediaPlayer 已重置并且没有再次准备好。
提前致谢 :)