【问题标题】:play or pause multiple audio files in android在android中播放或暂停多个音频文件
【发布时间】:2013-04-24 08:40:22
【问题描述】:

我有一个关于在 android 中播放/暂停多个音频文件的问题。我们的应用程序使用 restful api 从服务器加载音频文件。在 api 中会有访问音频文件的链接(如http://www.common.com/folder/folder1/file1.mp4)。我们的应用程序将在 android 活动的列表视图中列出音频文件的名称。一旦用户点击 file1 然后 file1 开始播放。当用户点击另一个文件时,file1 会暂停播放并开始播放被点击的文件。这应该发生在所有文件上。

我们的疑问是,我们是否需要使用媒体播放器的多个实例来播放不同的音频文件。像每个文件的新 MediaPlayer() 对象一样吗?我们可以用一个 MediaPlayer 实例来处理这种情况吗? SoundPool 在这种情况下有帮助吗?

【问题讨论】:

    标签: android android-mediaplayer


    【解决方案1】:

    是的,如果您想要这个播放/暂停过程,Soundpool 可能会有所帮助。

    首先,您创建一个跨活动实例保留的声音管理器,以及一个将音频文件链接到 ID 的映射。

    // Replace 10 with the maximum of sounds that you would like play at the same time.
    SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 100); 
    HashMap<String, Integer> stringToSoundID = new HashMap<String, Integer>();
    HashMap<Integer, Integer> soundIdToStreamID = new HashMap<Integer, Integer>();
    Integer streamIDbeingPlayed= -1;
    

    然后将所有声音加载到 soundPool 中,保持文件和声音 ID 之间的链接。

    for(String filePath: Files) {
      int soundID = soundPool.load(filePath, 1);
      stringToSoundID.put(filePath, soundID );
    }
    

    然后你可以让你的函数像这样播放/暂停文件:

    void playFile(String filePath) {
      if(streamIDbeingPlayed!= -1) {
        soundPool.pause(streamIDbeingPlayed);
      }
      Integer soundID = stringToSoundID.get(filePath);
      Integer streamID = soundIdToStreamID.get(soundID);
      if(streamID == null) {
        streamIDbeingPlayed = soundPool.play (soundID, 1, 1, 1, -1, 1);
        soundIdToStreamID.put(soundID, streamIDbeingPlayed);
      } else {
        soundPool.resume(streamID);
        streamIDbeingPlayed = streamID;
      }
    }
    

    【讨论】:

    • 感谢您的回答。但是当我们使用 soundpool 时,它不会返回播放的当前位置和音频的总持续时间。我用于更新进度条的这些详细信息...
    • SoundPool 用于小音频文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多