在 Android 中使用 MediaPlayer 播放多种声音的正确方法是什么?
What's the proper way to use the MediaPlayer in Android for multiple sounds?
我想在用户输入时播放多个原始声音。我使用文档中的示例:
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start();
但是因为我有多个声音,每次我想播放不同的声音时我应该做 MediaPlayer.create(...),还是应该实例化多个 MediaPlayer 对象并只调用 start()我想玩?
我想我问的是在需要时实例化与保留在内存中的成本。
如果要使用多个小音,其实用SoundPool反而更好:
AudioAttributes audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_GAME)
.build();
SoundPool soundPool = new SoundPool.Builder()
.setAudioAttributes(audioAttributes)
.build();
int id = soundPool.load(context, resourceId, 0);
soundPool.play(id, 1, 1, 0, 0, 1);
但是如果你真的需要我的问题的答案,我会说你应该将 MediaPlayer 保存在内存中,在 运行 上实例化它会减慢你的应用程序并延迟声音。
我想在用户输入时播放多个原始声音。我使用文档中的示例:
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start();
但是因为我有多个声音,每次我想播放不同的声音时我应该做 MediaPlayer.create(...),还是应该实例化多个 MediaPlayer 对象并只调用 start()我想玩?
我想我问的是在需要时实例化与保留在内存中的成本。
如果要使用多个小音,其实用SoundPool反而更好:
AudioAttributes audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_GAME)
.build();
SoundPool soundPool = new SoundPool.Builder()
.setAudioAttributes(audioAttributes)
.build();
int id = soundPool.load(context, resourceId, 0);
soundPool.play(id, 1, 1, 0, 0, 1);
但是如果你真的需要我的问题的答案,我会说你应该将 MediaPlayer 保存在内存中,在 运行 上实例化它会减慢你的应用程序并延迟声音。