Android Using SoundPool to Play Sound Instances

  • 2021-11-14 06:54:36
  • OfStack

Usage scenario

SoundPool1 is used to play dense, rapid and short-lived sound effects, such as special sound effects: Duang ~, which is used more in games. You can also add this sound effect to your APP, such as playing "Hello, Cool Dog" when cool dog music goes in. Is it interesting for SoundPool

ok, let's not talk too much. Please see the notes for detailed parameter explanation


public class SoundPlayer extends AppCompatActivity {

  private SoundPool mSoundPool;


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sound_player);

    initState();
  }

  private void initState() {
    //sdk版本21是SoundPool 的1个分水岭
    if (Build.VERSION.SDK_INT >= 21) {
      SoundPool.Builder builder = new SoundPool.Builder();
      //传入最多播放音频数量,
      builder.setMaxStreams(1);
      //AudioAttributes是1个封装音频各种属性的方法
      AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
      //设置音频流的合适的属性
      attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
      //加载1个AudioAttributes
      builder.setAudioAttributes(attrBuilder.build());
      mSoundPool = builder.build();
    } else {
      /**
       * 第1个参数:int maxStreams:SoundPool对象的最大并发流数
       * 第2个参数:int streamType:AudioManager中描述的音频流类型
       *第3个参数:int srcQuality:采样率转换器的质量。 目前没有效果。 使用0作为默认值。
       */
      mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    }

    //可以通过4种途径来记载1个音频资源:
    //context:上下文
    //resId:资源id
    // priority:没什么用的1个参数,建议设置为1,保持和未来的兼容性
    //path:文件路径
    // FileDescriptor:貌似是流吧,这个我也不知道
    //:从asset目录读取某个资源文件,用法: AssetFileDescriptor descriptor = assetManager.openFd("biaobiao.mp3");

    //1.通过1个AssetFileDescriptor对象
    //int load(AssetFileDescriptor afd, int priority)
    //2.通过1个资源ID
    //int load(Context context, int resId, int priority)
    //3.通过指定的路径加载
    //int load(String path, int priority)
    //4.通过FileDescriptor加载
    //int load(FileDescriptor fd, long offset, long length, int priority)
    //声音ID 加载音频资源,这里用的是第2种,第3个参数为priority,声音的优先级*API中指出,priority参数目前没有效果,建议设置为1。
    final int voiceId = mSoundPool.load(this, R.raw.duang, 1);
    //异步需要等待加载完成,音频才能播放成功
    mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
      @Override
      public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
        if (status == 0) {
          //第1个参数soundID
          //第2个参数leftVolume为左侧音量值(范围= 0.0到1.0)
          //第3个参数rightVolume为右的音量值(范围= 0.0到1.0)
          //第4个参数priority 为流的优先级,值越大优先级高,影响当同时播放数量超出了最大支持数时SoundPool对该流的处理
          //第5个参数loop 为音频重复播放次数,0为值播放1次,-1为无限循环,其他值为播放loop+1次
          //第6个参数 rate为播放的速率,范围0.5-2.0(0.5为1半速率,1.0为正常速率,2.0为两倍速率)
          soundPool.play(voiceId, 1, 1, 1, 0, 1);
        }
      }
    });
  }
  }

Very simple to use.


Related articles: