Android Plays Short Sound Effects Using SoundPool

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

Preface

For Android to play a short sound effect, such as a prompt tone or a ringtone, SoundPool can save more resources than using MediaPlayer, and can play multiple sound effects at the same time, and can set different playback qualities for different sound effects

Realization

The specific function of SoundPool will not be described, and the code will be posted 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); // Maximum playback 10 Sound effects in the format of Steam_music The sound quality is 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));  // Add the resources you want to play to the SoundPool And save the returned StreamID , through StreamID You can stop a sound effect 
    }


 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, 0, -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);
    }
}

Related articles: