以前播放音频都是使用MediaPlayer来播放,但MediaPlayer的创建和销毁都是非常销毁资源的,如果要播放一些短的音频,使用MediaPlayer就不太合适了。这个时候我们就需要用到SoundPool;

public class SoundPool extends Object

a.初始化SoundPool

SoundPool soundPool = new SoundPool(maxStreams, streamType, srcQuality);

参数:

参数 解释
maxStreams 最大的流的数量
streamType 流的类型(一般AudioManager.STREAM_SYSTEM)
srcQuality 频的质量,默认是0,目前没有影响

streamType :
1. STREAM_ALARM
2. STREAM_DTMF
3. STREAM_MUSIC
4. STREAM_NOTIFICATION
5. STREAM_RING
6. STREAM_SYSTEM
7. STREAM_VOICE_CALL

b.加载音频

返回值 方法 解释
int load (AssetFileDescriptor afd, int priority) Load the sound from an asset file descriptor
int load (String path, int priority) Load the sound from the specified path
int load (Context context, int resId, int priority) Load the sound from the specified APK resource
int load (FileDescriptor fd, long offset, long length, int priority) Load the sound from a FileDescriptor

一般使用load(Context context, int resId, int priority)方法加载音频:
context : 上下文;
resId :音频文件地址(R.raw.xxx);
priority : 声音优先级,默认1即可。

c.音频播放

int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) 

soundId : 音频的ID,load()的返回值;
leftVolume : 左声道值(范围= 0.0到1.0);
rightVolue : 右声道值(范围= 0.0到1.0);
priority : 流优先级(0 是最低优先级);
loop : 循环播放次数,0为不循环,-1为永远循环;
rate : 播放速率(1.0 是正常播放,范围0.5至2.0).

d.代码总结

//初始化SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);//加载音频文件soundId = soundPool.load(context, R.raw.xxx, 1);//播放音频文件int res = soundPool.play(soundId, 0.3f, 0.3f, 1, -1, 1);//停止播放音频soundPool.stop(res);

e.资源释放

@Overrideprotected void onDestroy(){    super.onDestroy();    if(soundPool != null){        soundPool.release();    }}

更多相关文章

  1. Android(安卓)API学习 SoundPool 和 MediaPlayer
  2. android 录音 mediaRecorder
  3. 实现简单的Android的播放视频功能
  4. Android多媒体开发高级编程
  5. android 播放音乐示例
  6. BiliBili-IJKPlayer播放器源码分析(一)
  7. android中调用系统功能 来显示本地相册图片 拍照 视频 音频功能
  8. android 酷狗demo_高仿酷狗音乐播放器Android源码完整版
  9. android非常好的在线视频播放器源码(包含在线音频播放源码)

随机推荐

  1. 【Android】adb常用指令整理
  2. android TextView中多个空格只显示一个
  3. Android控件GridView的使用
  4. Android——TV真机调试apk(android:shared
  5. Android(安卓)自定义TextView 实现文本间
  6. Bing Maps Android(安卓)SDK Released
  7. android获取GPS位置信息
  8. android:layout_gravity="bottom"不起作
  9. 《Android开发从零开始》——13.Table La
  10. PreferenceActivity和PreferenceFragment