Android使用SoundPool播放音效实例

前端之家收集整理的这篇文章主要介绍了Android使用SoundPool播放音效实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用场景

SoundPool一般用来 播放密集,急促而又短暂的音效,比如特技音效:Duang~,游戏用得较多,你也可以为你的 APP添加上这个音效,比如酷狗音乐进去的时候播放"哈喽,酷狗" 是不是提起了对于SoundPool的兴趣了呢

ok,废话不多说 详细的参数解释请看注释

  1. public class SoundPlayer extends AppCompatActivity {
  2.  
  3. private SoundPool mSoundPool;
  4.  
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_sound_player);
  9.  
  10. initState();
  11. }
  12.  
  13. private void initState() {
  14. //sdk版本21是SoundPool 的一个分水岭
  15. if (Build.VERSION.SDK_INT >= 21) {
  16. SoundPool.Builder builder = new SoundPool.Builder();
  17. //传入最多播放音频数量,builder.setMaxStreams(1);
  18. //AudioAttributes是一个封装音频各种属性方法
  19. AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
  20. //设置音频流的合适的属性
  21. attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
  22. //加载一个AudioAttributes
  23. builder.setAudioAttributes(attrBuilder.build());
  24. mSoundPool = builder.build();
  25. } else {
  26. /**
  27. * 第一个参数:int maxStreams:SoundPool对象的最大并发流数
  28. * 第二个参数:int streamType:AudioManager中描述的音频流类型
  29. *第三个参数:int srcQuality:采样率转换器的质量。 目前没有效果。 使用0作为默认值。
  30. */
  31. mSoundPool = new SoundPool(1,AudioManager.STREAM_MUSIC,0);
  32. }
  33.  
  34. //可以通过四种途径来记载一个音频资源:
  35. //context:上下文
  36. //resId:资源id
  37. // priority:没什么用的一个参数,建议设置为1,保持和未来的兼容性
  38. //path:文件路径
  39. // FileDescriptor:貌似是流吧,这个我也不知道
  40. //:从asset目录读取某个资源文件用法: AssetFileDescriptor descriptor = assetManager.openFd("biaobiao.mp3");
  41.  
  42. //1.通过一个AssetFileDescriptor对象
  43. //int load(AssetFileDescriptor afd,int priority)
  44. //2.通过一个资源ID
  45. //int load(Context context,int resId,int priority)
  46. //3.通过指定的路径加载
  47. //int load(String path,int priority)
  48. //4.通过FileDescriptor加载
  49. //int load(FileDescriptor fd,long offset,long length,int priority)
  50. //声音ID 加载音频资源,这里用的是第二种,第三个参数为priority,声音的优先级*API中指出,priority参数目前没有效果,建议设置为1。
  51. final int voiceId = mSoundPool.load(this,R.raw.duang,1);
  52. //异步需要等待加载完成,音频才能播放成功
  53. mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
  54. @Override
  55. public void onLoadComplete(SoundPool soundPool,int sampleId,int status) {
  56. if (status == 0) {
  57. //第一个参数soundID
  58. //第二个参数leftVolume为左侧音量值(范围= 0.0到1.0)
  59. //第三个参数rightVolume为右的音量值(范围= 0.0到1.0)
  60. //第四个参数priority 为流的优先级,值越大优先级高,影响当同时播放数量超出了最大支持数时SoundPool对该流的处理
  61. //第五个参数loop 为音频重复播放次数,0为值播放一次,-1为无限循环,其他值为播放loop+1次
  62. //第六个参数 rate为播放的速率,范围0.5-2.0(0.5为一半速率,1.0为正常速率,2.0为两倍速率)
  63. soundPool.play(voiceId,1,1);
  64. }
  65. }
  66. });
  67. }
  68. }

非常简单的使用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

猜你在找的Android相关文章