我的应用程序 acitvity 中有很多 Mediaplayer 声音,我有按钮可以停止所有正在播放的声音,但它占用了大量空间,我想知道如何同时停止所有 mediplayer 声音的代码 < strong>不是这样的:
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);
最佳答案
对于此目的,SoundPool 是一个更好的选择。我强烈反对实例化多个 MediaPlayer 实例,因为大多数系统没有资源来生成许多并行 Activity 实例。您会发现在许多设备上按下按钮 5 次以上会导致基于内存的崩溃。
就停止所有 Activity 流而言,没有为此内置的功能,但可以通过类似于现有代码的方式轻松完成。作为旁注,有一个 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() 也是安全的,因此您无需检查现有播放。
关于android - 如何停止 Activity 中的所有声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29919101/