2

I'm developing an android application which is collection of 100 sound effects. After I play for instance 25 of the sounds, I can't play anymore and I have to close the application and wait for some minutes then open the application and now I can play other sounds.

final MediaPlayer mp81 = MediaPlayer.create(MainActivity.this, R.raw.a81);

I play the sound using the below code:

mp81.start();

I stop the playing sound using the below code:

mp81.seekTo(0);

I also used stop() method but the problem were still existing. is there any other method i have to add?

sgarizvi
  • 16,623
  • 9
  • 64
  • 98
Amin Sajedi
  • 135
  • 9

1 Answers1

3

Please note: consider using SoundPool for playing short sounds.

Regarding your use-case: you initialize your MediaPlayer instance using the static create() method which means you create a new MediaPlayer object for each sound instead of reusing an existing instance and just changing the data source. This might negatively affect the performance of your app. I suggest that you create an array of paths to your sounds and then instantiate the MediaPlayer like this:

MediaPlayer mp = new MediaPlayer();
try {
     mp.setDataSource(yourArray[x]);
     mp.prepare();
     mp.start();
  } catch(Exception e){
    e.printStackTrace();
  }

Consult the MediaPlayer Document for more information.

Droidman
  • 11,485
  • 17
  • 93
  • 141
  • I followed what you said but unfortunately I'm still having the problem and the app also force closes soon – Amin Sajedi Mar 08 '13 at 12:21
  • please post your updated code and LogCat messages that appear when your app crashes – Droidman Mar 08 '13 at 12:27
  • this is the code i have written based on what you mentioned above. the problem is that when running the application no sound is played and the logcat says: setDataSource called in state 8 look at my code in the answer section below.... – Amin Sajedi Mar 09 '13 at 10:44
  • public void onClick(View v) { mp = MediaPlayer.create(Main.this, R.raw.a1); if (i[0] == false) {try {mp.setDataSource(source[0].toString());mp.start();} catch (Exception e) {e.printStackTrace();} b1.setBackgroundResource(R.drawable.stop_button); i[0] = true;}else{mp.stop(); b1.setBackgroundResource(R.drawable.horn); i[0] = false;}}}); – Amin Sajedi Mar 09 '13 at 10:55
  • try to initialize the MediaPlayer using new and then calling prepare() or prepareAsync(). And I strongly recommend you to consult the API documentation I linked, MediaPlayer is trickier than it may seem – Droidman Mar 09 '13 at 19:46