【问题标题】:Android - Playing multiple sounds sequenciallyAndroid - 按顺序播放多个声音
【发布时间】:2012-07-07 12:31:34
【问题描述】:

我需要在活动运行时发出许多小声音。 某些文件每隔固定时间间隔播放一次(例如 5 秒) 当触摸屏幕时,一些文件将在一个完成下一次启动(例如 sound1、sound2、sound3)时按顺序播放。

总声音约为 35 个短 mp3 文件(最长 3 秒)。

实现这一点的最佳方法是什么?

谢谢

【问题讨论】:

    标签: android audio


    【解决方案1】:

    SoundPool 常用于播放多个短音。您可以在 onCreate() 中加载所有声音,将它们的位置存储在 HashMap 中。

    创建 SoundPool

    public static final int SOUND_1 = 1;
    public static final int SOUND_2 = 2;
    
    SoundPool mSoundPool;
    HashMap<Integer, Integer> mSoundMap;
    
    @Override
    public void onCreate(Bundle savedInstanceState){
      mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
      mSoundMap = new HashMap<Integer, Integer>();
    
      if(mSoundPool != null){
        mSoundMap.put(SOUND_1, mSoundPool.load(this, R.raw.sound1, 1));
        mSoundMap.put(SOUND_2, mSoundPool.load(this, R.raw.sound2, 1));
      }
    }
    

    然后,当您需要播放声音时,只需调用 playSound() 并使用声音的常量值。

    /*
    *Call this function from code with the sound you want e.g. playSound(SOUND_1);
    */
    public void playSound(int sound) {
        AudioManager mgr = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = streamVolumeCurrent / streamVolumeMax;  
    
        if(mSoundPool != null){
            mSoundPool.play(mSoundMap.get(sound), volume, volume, 1, 0, 1.0f);
        }
    }
    

    【讨论】:

      【解决方案2】:

      MediaPlayer 具有PlaybackCompleted 状态,因此当一个音频结束时,您可以开始播放另一个

      public void setOnCompletionListener (MediaPlayer.OnCompletionListener listener)
      

      source

      我会尝试ThreadAsyncTask 分别播放不同的音频线

      【讨论】:

      • 谢谢,我相信应该有更好更有效的方法来做到这一点。这是因为我必须为每个文件“准备”媒体播放器。这就是我提到手头文件数量的原因。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      • 2019-07-29
      • 2013-02-05
      • 2012-02-16
      相关资源
      最近更新 更多