How to stop all sounds in activity?

大憨熊 提交于 2021-01-28 01:25:41

问题


I have a lot of Mediaplayer sounds in my application acitvity and i have button to stop all sounds that are playing but its taking a lot of space and i want to know the code how to stop all the mediplayer sounds at same time not like this:

    sadegfqc.pause();
    dsfsdf.pause();
    sadfsadfsad.pause();
    dsfg.pause();
    htzh.pause();
    nensmene.pause();
    fdshs.pause();
    gshtrhtr.pause();
    hfshztjr.pause();
    sgawg.pause();

And then i have to call all the creates of Mediaplayer with a source again. like this:

dsfsadf= MediaPlayer.create(this, R.raw.dsfsadf);

回答1:


SoundPool is a much better alternative for this purpose. I would caution strongly against instantiating multiple MediaPlayer instances as most systems do not have the resources to generate many parallel active instances. You wil find on many device that hitting the button upwards of 5 times will cause a memory based crash.

As far as stopping all active streams, there is not baked-in function for this, but it's easy to accomplish in a manner to similar to your existing code. As a side note, there is an autoPause() method, which halts all streams, but it doesn't truly end their playback (as the method name insinuates). Here is a simple example to manage your audio streams:

//SoundPool initialization somewhere
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
//Load your sound effect into the pool
int soundId = pool.load(...); //There are several versions of this, pick which fits your sound

List<Integer> streams = new ArrayList<Integer>();
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
   public void onClick(View view) {
       int streamId = pool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
       streams.add(streamId);
   }
});

Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
   public void onClick(View view) {
      for (Integer stream : streams) {
          pool.stop(stream);
      }
      streams.clear();
   }
});

It is much more memory efficient to manage a list of streamID values than MediaPlayer instances, and your users will thank you. Also, note that it is safe to call SoundPool.stop() even if the streamID is no longer valid, so you don't need to check for existing playback.



来源:https://stackoverflow.com/questions/29919101/how-to-stop-all-sounds-in-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!