Android SoundPool基本使用

一、SoundPool相对于MediaPlayer的优点
1.SoundPool适合 短且对反应速度比较高 的情况(游戏音效或按键声等),文件大小一般控制在几十K到几百K,最好不超过1M,
2.SoundPool 可以与MediaPlayer同时播放,SoundPool也可以同时播放多个声音;
3.SoundPool 最终编解码实现与MediaPlayer相同;
4.MediaPlayer只能同时播放一个声音,加载文件有一定的时间,适合文件比较大,响应时间要是那种不是非常高的场景
二、SoundPool API简单说明
SoundPool使用其来播放音乐
1、构造方法

SoundPool (int maxStreams,  int streamType, int srcQuality)
//maxStreams 设置soundpool对象的并发流的最大数量
//streamType 设置流的类型,一般为STREAM_MUSIC
//srcQuality 采样转换率的质量  现在没有什么效果 0 设为默认

2、常用方法(加载音频文件)

与MediaPlayer相同 SoundPool 加载音频文件有多种方式

<!--加载应用资源文件--> 注意:切忌使用文件名相同,格式名不同的文件example.mp3  ,example.wav
int	load(Context context, int resId, int priority)

<!--从音频文件路径加载-->
int	load(String path, int priority)

<!--从asset 文件中加载-->
int	load(AssetFileDescriptor afd, int priority)

<!--从文件中加载-->
int	load(FileDescriptor fd, long offset, long length, int priority)

stop(int streamID)

pause(int streamID)

resume(int streamID)

release()

<!--设置循环播放  (0 不循环, -1 循环)-->
setLoop(int streamID, int loop)

<!--设置有播放优先级-->
setPriority(int streamID, int priority)

<!--设置播放播放速度 rate值 0.5 ~2.0 之间--> 
setRate(int streamID, float rate)

setVolume(int streamID, float leftVolume, float rightVolume)

<!--相对于load方法-->
unload(int soundID)

<!--此方法会遍历所有正在播放的音乐  并设置flag ,在autoResume的时候恢复播放-->
autoPause()
autoResume()

三、SoundPool 简单使用

public class MainActivity extends AppCompatActivity {
    HashMap<Integer, Integer> soundMap = new HashMap<>();
    SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button) ;
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soundPool.play(soundMap.get(0), 1, 1, 1, 0, 1);
            }
        });
        loadAudioResource();
    }
    private void loadAudioResource(){
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        if(soundMap.size() > 0){
            soundMap.clear();
        }
        soundMap.put(0, soundPool.load(this, R.raw.warning_lane, 2));
        soundMap.put(1, soundPool.load(this, R.raw.warning_car, 3));
        soundMap.put(2, soundPool.load(this, R.raw.warning_stopgo, 1));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值