I'm displaying a ListView of files to be played, read from an array in Strings.xml.
Everything works fine, however I can't figure out how to implement an Event which would stop the playback on Click or Touch anywhere on the screen, so the audio file can be interrupted and there's no need to wait until the whole file is played.
Please advise.
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();
}
});
}
}
Instead of playing the media in the onItemClick()
, create an AsyncTask to start it in the background, then flag the background thread to stop when the user indicates they want to stop (clicking a button say). Alternatively control the player through a Service and make calls to stop/start the player through that, as you really don't want the player to be running on the UI thread.
Here's an example using AsyncTask that will stop playing when the user clicks a button (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;
}
}