【问题标题】:How to stop all sounds in activity?如何停止活动中的所有声音?
【发布时间】:2015-04-28 12:09:39
【问题描述】:

我的应用程序活动中有很多 Mediaplayer 声音,我有按钮来停止所有正在播放的声音,但它占用了大量空间,我想知道如何同时停止所有 mediplayer 声音的代码 不是这样的:

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

然后我必须再次使用源调用 Mediaplayer 的所有创建。 像这样:

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

【问题讨论】:

标签: android audio media-player onpause


【解决方案1】:

SoundPool 是一个更好的选择。我强烈警告不要实例化多个 MediaPlayer 实例,因为大多数系统没有资源来生成许多并行活动实例。您会发现在许多设备上点击按钮超过 5 次会导致基于内存的崩溃。

就停止所有活动流而言,没有内置的功能,但很容易以类似于您现有代码的方式完成。附带说明一下,有一个 autoPause() 方法可以停止所有流,但它并没有真正结束它们的播放(正如方法名称所暗示的那样)。下面是一个管理音频流的简单示例:

//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();
   }
});

与 MediaPlayer 实例相比,管理 streamID 值列表的内存效率要高得多,您的用户会感谢您的。另外,请注意,即使 streamID 不再有效,调用 SoundPool.stop() 也是安全的,因此您无需检查现有播放。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    相关资源
    最近更新 更多