【问题标题】:What's the proper way to use the MediaPlayer in Android for multiple sounds?在 Android 中使用 MediaPlayer 播放多种声音的正确方法是什么?
【发布时间】:2018-04-30 13:51:47
【问题描述】:

我有多个想要在用户输入时播放的原始声音。我使用文档中的示例:

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start();

但是由于我有多个声音,我应该每次想要播放不同的声音时都执行 MediaPlayer.create(...),还是应该实例化多个 MediaPlayer 对象并只调用我想要播放的 start() ?

我想我问的是在需要时实例化与保留在内存中的成本。

【问题讨论】:

    标签: android android-mediaplayer


    【解决方案1】:

    如果你想使用多个小声音,实际上最好使用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 保存在内存中,在运行时实例化它会减慢你的应用程序并延迟声音。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多