Reputation: 342
I don't know why it doesn't works, there is no error logged in logcat, but I cannot hear a sound.
public static void DeclararSonido(int numero, Context contexto){
switch(numero){
case 0:
mp = MediaPlayer.create(contexto, R.raw.alan);
break;
}
}
public static void TocarPiedra( int posicion, Context contexto){
DeclararSonido(posicion, contexto);
mp.start();
mp.stop();
mp.release();
}
public static void TocarSirena(Context contexto){
MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);
mp2.start();
mp2.stop();
mp2.release();
}
If I erase mp2.stop();
and mp2.release();
AND mp.stop();
and mp.release();
the app plays the sound, but the file is not released...
Upvotes: 4
Views: 11340
Reputation: 55760
You certainly do not want to Start and then Stop right away..
The problem is that you are executing these right after each other:
mp.start(); // starts playback
mp.stop(); // .. then stops immediately ..
mp.release();
You should call start, and then when the sound is done playing, release. You can use the Completion event to hook up a listener and release there:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer player) {
player.release();
}
})
Upvotes: 11
Reputation: 773
Mediaplayer.create():- creates the new object of mediaplayer .this object is having music file from raw folder which is to be played when start() method is called
Mediaplayer.start():- *starts playing music* if object Mediaplayer is initialized .otherwise gives exception.
Mediaplayer.stop() :-*stops* the current ongoing music with that object.
Mediaplayer.release():-the music file path is no longer associated with Mediaplayer object. so u need to reallocate memory and all. mind it mediaplayer would not be null .
go here and see the state diagram of mediaplayer
Now what you are doing is that starting the song and directly stopping it .I would suggest you to create button , and when button is pressed stop the mediaplayer.
Other way is already given by Miky Dinescu that setoncompletelistner.
so, do as follows
public static void DeclararSonido(int numero, Context contexto){
switch(numero){
case 0:
mp = MediaPlayer.create(contexto, R.raw.alan);
break;
}
}
public static void TocarPiedra( int posicion, Context contexto){
DeclararSonido(posicion, contexto);
mp.start();
mp.setOnCompleteListener(new OnCompleteListener(){
public void OnCompletion(MediaPlayer mp){
mp.stop();
mp.release();
}});
}
public static void TocarSirena(Context contexto){
MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);
//Alomejor es por la extension
mp2.start();
mp2.setOnCompleteListener(new OnCompleteListener(){
public void OnCompletion(MediaPlayer mp){
mp2.stop();
mp2.release();
}});
}
Upvotes: 2