Android uses soundpool to play short sound effects

preface

For Android to play some short sound effects, such as prompt tone or ring tone, soundpool can save more resources than using mediaplayer, play multiple sound effects at the same time, and set different playback quality for different sound effects

realization

The specific function of soundpool will not be described, but the code will be pasted directly

private SoundPool.Builder spBuilder;
private SoundPool soundPool;
private Integer[] fmSound = FmManager.getRawAudios();

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      if (null == spBuilder) {
        spBuilder = new SoundPool.Builder();
        AudioAttributes.Builder builder = new AudioAttributes.Builder();
        builder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
        spBuilder.setAudioAttributes(builder.build());
        spBuilder.setMaxStreams(10);
      }
      if (null == soundPool) {
        soundPool = spBuilder.build();
      }
    } else {
      if (null == soundPool) {
        soundPool = new SoundPool(10,AudioManager.STREAM_MUSIC,10); //最多播放10个音效,格式为Steam_music,音质为10
      }
    }
    soundPool.setOnLoadCompleteListener(this);
    if (null == fmArray) {
      fmArray = new SparseIntArray();
    }
    if (null == streamArray) {
      streamArray = new SparseIntArray();
    }
    for (int i = 0; i < fmSound.length; i++) {
      fmArray.put(i + 1,soundPool.load(this,fmSound[i],1));  //将需要播放的资源添加到SoundPool中,并保存返回的StreamID,通过StreamID可以停止某个音效
    }

 private void playFmByPosition(int resultId) {
    if (null == soundPool || resultId < 0 || fmArray == null || fmArray.size() < 0 || streamArray == null)
      return;
    LogUtils.e(resultId + "------------" + fmArray.size());

    if (resultId < fmArray.size()) {
      if (!FmPlaying.isPlay(resultId)) {
        int fmPlayId = soundPool.play(fmArray.get(resultId + 1),1,-1,1);
        streamArray.put(resultId,fmPlayId);
        FmPlaying.setPlay(resultId,true);
      } else {
        soundPool.stop(streamArray.get(resultId));
        streamArray.removeAt(resultId);
        FmPlaying.setPlay(resultId,false);
      }
    }
  }

  static class FmPlaying {
    private static SparseBooleanArray playArray = new SparseBooleanArray();

    public static boolean isPlay(int position) {
      return playArray.get(position,false);
    }

    public static void setPlay(int position,boolean play) {
      playArray.put(position,play);
    }
}

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>