我正在显示要播放的文件的ListView,从Strings.xml中的数组中读取。
一切正常,但我无法弄清楚如何实现一个可以在屏幕上的任何地方停止播放Click或Touch的事件,因此音频文件可以被中断并且不需要等到整个文件播放。
请告知。
public class ViewSounds extends ListActivity {
MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Get Button Labels
String[] lex_names = getResources().getStringArray(R.array.lex_names);
// Get File Names
final String[] lex_files = getResources().getStringArray(R.array.lex_files);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_sounds, lex_names));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int playFile = getResources().getIdentifier(lex_files[position], "raw", getPackageName());
mp = MediaPlayer.create(getApplicationContext(), playFile);
mp.start();
while (mp.isPlaying()) {
// ...
};
mp.release();
}
});
}
}
答案 0 :(得分:0)
不是在onItemClick()
中播放媒体,而是创建一个AsyncTask以在后台启动它,然后标记后台线程以在用户指示他们想要停止时停止(单击按钮说)。或者通过服务控制播放器,并通过它调用停止/启动播放器,因为你真的不希望播放器在UI线程上运行。
以下是使用AsyncTask的示例,当用户单击按钮时会停止播放(R.id.stop_playing):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MediaPlayerAsyncTask player = new MediaPlayerAsyncTask(R.raw.my_media);
Button stopPlaying = (Button) findViewById(R.id.stop_playing);
stopPlaying.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
player.stopPlayer();
}
});
setVolumeControlStream(AudioManager.STREAM_MUSIC);
player.execute((Void []) null);
}
private class MediaPlayerAsyncTask extends AsyncTask<Void, Void, Void> {
private boolean stopPlayer;
MediaPlayer mp;
MediaPlayerAsyncTask(int playFile) {
mp = MediaPlayer.create(TestStuff.this, playFile);
}
@Override
protected Void doInBackground(Void... params) {
stopPlayer = false;
mp.start();
while (!stopPlayer && mp.isPlaying()) {
SystemClock.sleep(1000);
}
mp.stop();
return null;
}
public void stopPlayer() {
stopPlayer = true;
}
}