How To Use Sound With Toast In Android
I want to play a sound when my toast pops up in my android app. Here is my code for the toast in my main class: private void workEndNotification() { //Custom Toast notification
Solution 1:
Make a function like this
privatevoidplaySound(int resId){
mp = MediaPlayer.create(MainActivity.this, resId);
mp.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
mediaPlayer.release();
}
});
mp.start();
}
and call it where you are displaying your Toast
like this
playSound(R.raw.sound);
You also need to replace the resource so it matches yours
EDIT: You seem to want to play several sounds. You can make a simple sound pool on your own
Make a int array or resource you want to play like this and listen for when the MediaPlayer
is done with playing, tell him to play the next one until it played the last one in the array.
publicclassTestActivityextendsActivityimplementsMediaPlayer.OnCompletionListener {
privatefinalint[] soundResources = {R.raw.sound1, R.raw.sound2, R.raw.sound3};
privateintcounter=0;
private MediaPlayer mp;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
playSound(counter);
}
privatevoidplaySound(int resId){
mp = MediaPlayer.create(TestActivity.this, resId);
mp.setOnCompletionListener(this);
mp.start();
}
@OverridepublicvoidonCompletion(MediaPlayer mediaPlayer) {
mp.reset();
mp.release();
if(counter < soundResources.length ) {
playSound(soundResources[++counter]);
}
}
}
Post a Comment for "How To Use Sound With Toast In Android"