Android音频播放--SoundPool

本文详细介绍如何使用SoundPool播放短音频,包括初始化SoundPool、加载音频文件、播放音频、停止播放及资源释放等步骤,并提供了代码示例。

以前播放音频都是使用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.加载音频

返回值方法解释
intload (AssetFileDescriptor afd, int priority)Load the sound from an asset file descriptor
intload (String path, int priority)Load the sound from the specified path
intload (Context context, int resId, int priority)Load the sound from the specified APK resource
intload (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.资源释放

@Override
protected void onDestroy(){
    super.onDestroy();
    if(soundPool != null){
        soundPool.release();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值