SoundPoolUtil.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package com.xunao.effectdemo.utils;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.media.AudioManager;
  5. import android.media.SoundPool;
  6. /**
  7. * author : 程中强
  8. * e-mail : 740479946@qq.com
  9. * date : 2022/9/1617:28
  10. * desc : 语音播放工具类
  11. * version: 1.0
  12. */
  13. public class SoundPoolUtil {
  14. private volatile static SoundPoolUtil client;
  15. private SoundPool mSoundPool;
  16. private AudioManager mAudioManager;
  17. /*允许同时播放的音频数(为1时会立即结束上一个音频播放当前的音频)*/
  18. private static final int MAX_STREAMS = 1;
  19. // Stream type.
  20. private static final int streamType = AudioManager.STREAM_MUSIC;
  21. private int mSoundId;
  22. private int mResId;
  23. private Context mainContext;
  24. public static SoundPoolUtil getInstance(Context context) {
  25. if (client == null)
  26. synchronized (SoundPoolUtil.class) {
  27. if (client == null) {
  28. client = new SoundPoolUtil(context);
  29. }
  30. }
  31. return client;
  32. }
  33. private SoundPoolUtil(Context context) {
  34. this.mainContext = context;
  35. mAudioManager = (AudioManager) this.mainContext.getSystemService(Context.AUDIO_SERVICE);
  36. ((Activity) this.mainContext).setVolumeControlStream(streamType);
  37. this.mSoundPool = new SoundPool(MAX_STREAMS, streamType, 0);
  38. }
  39. /**
  40. * 播放音频
  41. * @param resId 本地音频资源
  42. */
  43. public void playSoundWithRedId(int resId) {
  44. this.mResId = resId;
  45. this.mSoundId = this.mSoundPool.load(this.mainContext, this.mResId, 1);
  46. this.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
  47. @Override
  48. public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
  49. playSound();
  50. }
  51. });
  52. }
  53. /**
  54. * 播放音频,但是当前有音频这正播放中时不响应该次音频播放
  55. * @param resId 本地音频资源
  56. */
  57. public synchronized void playSoundUnfinished(int resId) {
  58. if ( isFmActive()) return;
  59. this.mResId = resId;
  60. this.mSoundId = this.mSoundPool.load(this.mainContext, this.mResId, 1);
  61. mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
  62. @Override
  63. public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
  64. playSound();
  65. }
  66. });
  67. }
  68. /**
  69. * 播放音频文件
  70. */
  71. private void playSound() {
  72. mSoundPool.play(this.mSoundId, 1.0f, 1.0f, 0, 0, 1f);
  73. }
  74. /**
  75. * 判断当前设备是否正在播放音频
  76. */
  77. private boolean isFmActive() {
  78. if (mAudioManager == null) {
  79. return false;
  80. }
  81. return mAudioManager.isMusicActive();
  82. }
  83. }