I have an android app with a button that plays a sound. the code for playing the sound:
if (mp != null)
{
mp.release();
}
mp = MediaPlayer.create(this, R.raw.match);
mp.start();
mp is a field in the activity:
public class Game extends Activity implements OnClickListener {
/** Called when the activity is first created. */
//variables:
MediaPlayer mp;
//...
The app runs ok, but after clicking the button about 200 times on the emulator, app crashed and gave me this error https://dl.dropbox.com/u/5488790/error.txt (couldn't figure how to post it here so it will appear decently)
i am assuming this is because the MediaPlayer object is consuming up too much memory, but isn't mp.release() supposed to take care of this? What am i doing wrong here?
If you are attaching a sound effect to a button, MediaPlayer in general is far too heavyweight for this operation. You're getting unnecessary latency each time just to load up the sound data into memory. You should look at using SoundPool instead.
In either case, there is no valid reason to release and re-create the MediaPlayer each time. If you decide to use MediaPlayer, control the single instance you have with the button clicks.
MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Other init code
//Create the player this way so it doesn't auto-prepare
mp = new MediaPlayer();
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.match);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
}
public void onDestroy() {
super.onDestroy();
//Release it only when no longer needed
mp.release();
mp = null;
}
public void onButtonClick(View v) {
if (mp.isPlaying()) {
mp.stop();
}
//Play the sound
mp.prepare();
mp.start();
}
Hope that Helps, but again, I would highly recommend using SoundPool instead if this sound is just a short effect.
It looks like your code should work, but obviously release() isn't really releasing everything.
Maybe it's because you have to reload R.raw.match every time you want to play the sound. If R.raw.match is just a short sound effect, then you might want to consider using SoundPool instead.
If you use SoundPool you only have to load R.raw.match once which may prevent the memory issues.
This tutorial has a good example on how to use it: http://www.vogella.com/articles/AndroidMedia/article.html#tutorial_soundpool
You pretty much just make one instance of SoundPool then load the sound once and play it when you need it.
Hope this helps!
Edit
If you want to use MediaPlayer...
public class Blah extends Activity implements OnClickListener {
MediaPlayer mp;
#Override
public void onCreate(Bundle b)
{
// blah blah
mp = MediaPlayer.create(R.raw.match);
// blah blah
}
#Override
public void onClick(View v)
{
if (v.getId() == yourButtonID)
{
// play sound from beginning
mp.seekTo(0);
mp.start();
}
}
}
This way you only create one instance and whenever you want to play it, you just rewind it to the beginning then play.
Try
if (mp != null)
{
mp.release();
}
mp = MediaPlayer.create(this, R.raw.match);
mp.prepare(); // not needed
mp.start();
Good luck!!
if you hold the MediaPlayer, release it at the end of the activity
#Override
void onDestroy() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
super.onDestroy();
}
Related
I am developing a music player on android and the app has two activities (MainActivity and PlayActivity). In the MainActivity I have a listview with a list of songs and in the PlayActivity I have a button to listen and pause the music. The problem is that when go back to MainActivity and I select a new song from the listview, the first one keeps playing on background while the second one also starts playing. How can I stop the first song when I select a new one?
(I don't want to stop mediaplayer onBackPressed, I just want to stop the music when another song it's selected from listview and play a fresh song in PlayActivity)
EDIT: I'm using AsyncTask to start mediaplayer on PlayActivity: mp.prepareAsync();
You could try to stop MediaPlayer when onBackPressed()
MediaPlayer mp ; // mp is your MediaPlayer
#Override
public void onBackPressed() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
super.onBackPressed();
}
private void playMusic() {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
MediaPlayer copyMp = new MediaPlayer();
try {
copyMp.setDataSource("/path");
mp = copyMp;
mp.prepare();
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
From here
MediaPlayer is not thread-safe. Creation of and all access to player
instances should be on the same thread.
That means you have to maintain one media player instance throughout your whole application(As per your requirement). I don't know how you implemented the media player(Service/AsyncTask etc.). When you select a new song, you need to access that instance and replace the existing song with the selected one.
Currently I am using a mediaplayer to play one single audio file in a loop when a button is clicked( stops playing when a certain event is triggered or onstop). However, I am not sure if mediaplayer is ideal for playing 1 audio sound worth 8-10 seconds set to loop to a max of 30seconds. Is there a better and resource efficient alternative I can use? Any examples would help.
Here's my code so far:
MediaPlayer mp;
onCreate(savedinstance){
....
mp = MediaPlayer.create(getBaseContext(), R.raw.ringbacktone);
mp.setLooping(true);
mp.setVolume(100, 100);
...
}
public void somefunction {
...
case someeventhappens:
mp.start();
break;
...}
#Override
public void onStop() {
super.onStop();
mp.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mp != null) {
mp.stop();
}
Any idea how I can improve this or use a better resource efficient alternative to best suit my needs of just playing a .wav file ?
Thanks in advance!
I am trying to play two sound items, one after the other
MediaPlayer mp = null;
protected void produceErrorSound(int index) {
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, index);
mp.start();
}
public void correctAnswerAndNext(){
produceErrorSound(R.raw.right1) ;
produceErrorSound(R.raw.right1) ;
}
but only second sound is produced.
is there any alternative approach?
I can't see any wait mechanism in your code.
You can use an onCompletionListener to receive a callback when your first MediaPlayer has finished playback. At that point you can start the second MediaPlayer.
An alternative way in Jellybean (and later versions) is to use the audio chaining functionality (i.e. setNextMediaPlayer) to automatically start another MediaPlayer as soon as the current one has finished playing. Something like this (I've omitted the calls to setDataSource etc for brevity):
mediaPlayer1.prepare();
mediaPlayer2.prepare();
mediaPlayer1.start();
mediaPlayer1.setNextMediaPlayer(mediaPlayer2);
I have a game in which a sound plays when a level is completed. Everything works fine to start with but after repeating a level 10 or 20 times the logcat suddenly reports:
"MediaPlayer error (-19,0)" and/or "MediaPlayer start called in state 0" and the sounds are no longer made.
I originally had the all sounds in mp3 format but, after reading that ogg may be more reliable, I converted them all to ogg, but the errors appeared just the same.
Any idea how I can fix this problem?
I was getting the same problem, I solved it by adding the following code to release the player:
mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
I think you are not releasing the mediaplayers you are using to play the sound..
You need to release() the media players otherwise the resources are not released , and you soon get out of memory (since you allocate them again next time). so,I think you can play twice or even thrice... but not many times without releasing the resources
MediaPlayer is not a good option when you are playing small sound effects as the user can click on multiple buttons very soon and you will have to create a MP object for all of them which doesnt happen synchronously. That is why you are not hearing sounds for every click. Go for the SoundPool Class which allows you to keep smaller sounds loaded in memory and you can play them any time you want without any lag which you would feel in a mediaplayer. http://developer.android.com/reference/android/media/SoundPool.html Here is a nice tutorial : http://www.anddev.org/using_soundpool_instead_of_mediaplayer-t3115.html
I solved both the errors (-19,0) and (-38,0) , by creating a new object of MediaPlayer every time before playing and releasing it after that.
Before :
void play(int resourceID) {
if (getActivity() != null) {
//Using the same object - Problem persists
player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
After:
void play(int resourceID) {
if (getActivity() != null) {
//Problem Solved
//Creating new MediaPlayer object every time and releasing it after completion
final MediaPlayer player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
This is a very old question, But this came up first in my search results So other people with the same issue will probably come upon this page eventually.
Unlike what some others have said, you can in fact use MediaPlayer for small sounds without using a lot of memory. I'll put in a little modified snippit from my soundboard app to show you what I'm getting at.
private MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
mp = new MediaPlayer();
}
private void playSound(int soundID){
mp.reset();
AssetFileDescriptor sound = getResources().openRawResourceFd(soundID);
try {
mp.setDataSource(sound.getFileDescriptor(),sound.getStartOffset(),sound.getLength());
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
with the way I set it up, you create on MediaPlayer object that you reuse everytime you play a sound so that you don't use up too much space.
You call .reset() instead of .release() because .release() is only used if you are disposing of an object, however you want to keep your MediaPlayer Object.
You use an assetfiledescriptor to set a new soundfile for your mediaplayer to play instead of setting a new object to your mediaplayer address because that way you are creating new objects within the method that aren't being handled properly and you will eventually run into the same error as you described.
This is only one of many ways to use MediaPlayer but I personally think it is the most efficient if you are only using it for small sound applications. The only issue with it is that it is relatively restrictive in what you can accomplish, but that shouldn't be much of an issue if you are indeed using it for small sound applications.
i try delete emulator and new create emulator for remove error of (-19,0) media player.
I have got a MediaPlayer object as class attribute.
MediaPlayer mp;
Then I use them in my onCreate method -
mp = MediaPlayer.create(getApplicationContext(), R.raw.num1);
mp.start();
Then I try to stop it from one of my buttons clicklistener like this -
btnBack = (Button) findViewById(R.id.btn1);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopSound();
startActivity(new Intent(Five.this, Four.class));
finish();
}
});
}
public void stopSound(){
if (mp != null) {
mp.release();
mp.stop();
}
}
but the stop does not work.
What am i doing wrong?
You've already released the MediaPlayer instance. It's gone. You can't call stop() on it after you release it. If you plan to resume the sound, just remove the release() call. If you want to destroy the MediaPlayer (e.g. create a new one later with MediaPlayer.create()), remove the stop() call. You should read over this documentation pretty thoroughly; the MediaPlayer class is pretty complex. You need to understand the different states and when you can and cannot call certain methods.
In some android versions, just some ones, i had a similar issue in one app streamming radio, it worked it with:
try{
if(mp!=null && mp.isPlaying()){
mp.stop();
}
mp.release();
mp=null;
mp = new MediaPlayer(); //I needed this, maybe you dont hac
}catch(Exception e){
e.printStackTrace();
System.out.println("I can't believe you get here !");
}
you can't call release before stop
have a look at the lifecycle here http://developer.android.com/reference/android/media/MediaPlayer.html