首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >媒体播放器如何停止所有的声音?

媒体播放器如何停止所有的声音?
EN

Stack Overflow用户
提问于 2017-12-20 05:38:07
回答 1查看 1.3K关注 0票数 0

当我按下我创建的动作栏上的静音按钮时,它只会停止播放最后一个声音,而不是所有的声音。

另外,如果我按下按钮(5-6次)播放声音并在同一活动中按静音,那么声音就不会停止,然后返回并选择另一个活动,然后按那个静音按钮,应用程序就会崩溃。知道为什么吗?

代码语言:javascript
复制
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
public void pb1(View view) {
    mp = MediaPlayer.create(this, R.raw.sound1);
    mp.start();
  }
//inflates the menu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menunot, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_sound:
            mp.stop();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mp.stop();
    mp.reset();
    mp.release();
    mp = null;

}
EN

回答 1

Stack Overflow用户

发布于 2017-12-20 05:50:06

嘿,请试试下面的解决方案,

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

停止所有活动流()而言,并不存在此功能,但它很容易以类似于现有代码的方式完成。顺便提一句,有一个autoPause()方法,它停止所有流,但它并没有真正结束它们的回放(就像方法名暗示的那样)。下面是一个管理音频流的简单示例:

代码语言:javascript
复制
//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();
   }
});

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

快乐编码:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47899430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档