SoundPool 音频播放 API 详解【示例】
官方文档
API 介绍
SoundPool(int maxStreams, int streamType, int srcQuality) This constructor was deprecated in API level 21. use SoundPool.Builder instead to create and configure a SoundPool instance- maxStream:同时播放的流的最大数量
- streamType:流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出)
- srcQuality:采样率转化质量,当前无效果,使用0作为默认值
对指定streamID的播放进行控制
- final void pause(int streamID) Pause a playback stream. 暂停播放
- Pause the stream specified by the streamID. This is the value returned by the play() function. If the stream is playing, it will be paused. If the stream is not playing (e.g. is stopped or was previously paused), calling this function will have no effect. 暂停streamID指定的流。 这是play()函数返回的值。 如果流正在播放,它将被暂停。 如果流未播放(例如,停止或先前已暂停),则调用此功能将不起作用。
- final void resume(int streamID) Resume a playback stream. 继续播放
- Resume the stream specified by the streamID. This is the value returned by the play() function. If the stream is paused, this will resume playback. If the stream was not previously paused, calling this function will have no effect.
- final void stop(int streamID) Stop a playback stream. 终止播放
- Stop the stream specified by the streamID. This is the value returned by the play() function. If the stream is playing, it will be stopped. It also releases any native resources associated with this stream. If the stream is not playing, it will have no effect.
对指定streamID的参数进行设置
- final void setLoop(int streamID, int loop) Set loop mode. 设置指定播放流的循环次数
- A loop value of -1 means loop forever, a value of 0 means don't loop, other values indicate the number of repeats, e.g. a value of 1 plays the audio twice. If the stream does not exist, it will have no effect.
- final void setPriority(int streamID, int priority) Change stream priority. 设置指定播放流的优先级
- Change the priority of the stream specified by the streamID. This is the value returned by the play() function. Affects the order in which streams are re-used to play new sounds. If the stream does not exist, it will have no effect.
- final void setRate(int streamID, float rate) Change playback rate. 设置指定播放流的播放速率
- The playback rate allows the application to vary the playback rate (pitch) of the sound. A value of 1.0 means playback at the original frequency. A value of 2.0 means playback twice as fast, and a value of 0.5 means playback at half speed. If the stream does not exist, it will have no effect.
- final void setVolume(int streamID, float leftVolume, float rightVolume) Set stream volume. 设置指定播放流的音量大小
- Sets the volume on the stream specified by the streamID. This is the value returned by the play() function. The value must be in the range of 0.0 to 1.0. If the stream does not exist, it will have no effect.
全部流的暂停播放与恢复播放
- final void autoPause() Pause all active streams.
- Pause all streams that are currently playing. This function iterates through all the active streams and pauses any that are playing. It also sets a flag so that any streams that are playing can be resumed by calling autoResume(). 暂停正在播放的所有流。 此函数遍历所有活动流并暂停播放任何正在播放的流。 它还设置一个标志,以便可以通过调用autoResume()来恢复正在播放的任何流。
- final void autoResume() Resume all previously active streams.
- Automatically resumes all streams that were paused in previous calls to autoPause().
资源释放
- final boolean unload(int soundID) Unload a sound from a sound ID. 卸载一个指定的音频资源
- Unloads the sound specified by the soundID. This is the value returned by the load() function. Returns true if the sound is successfully unloaded, false if the sound was already unloaded.
- final void release() Release the SoundPool resources. 释放所有资源
- Release all memory and native resources used by the SoundPool object. The SoundPool can no longer be used and the reference should be set to null.
设置监听
- void setOnLoadCompleteListener(SoundPool.OnLoadCompleteListener listener) Sets the callback hook for the OnLoadCompleteListener.
- void onLoadComplete(SoundPool soundPool, int sampleId, int status) Called when a sound has completed loading.
加载音频资源【load】
- 通过一个资源ID,int load(Context context, int resId, int priority)
- 通过指定的路径,int load(String path, int priority)
- 通过一个AssetFileDescriptor对象,int load(AssetFileDescriptor afd, int priority)
- 通过FileDescriptor,int load(FileDescriptor fd, long offset, long length, int priority)
- int ; i < array.length; i++) {
array[i] = i + "、" + array[i];}setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<>(Arrays.asList(array))));soundPool = new SoundPool.Builder().setMaxStreams(5).setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()).build();soundPool.setOnLoadCompleteListener((soundPool1, sampleId, status) -> {Log.i("bqt", "【onLoadComplete】" + sampleId + " " + status);//status : 0 = success});new Thread(this::initReseResources).start();//在子线程中初始化,特别是当有大量资源需要初始化时}private void initReseResources() {Context context = this.getApplicationContext();//不管使用哪个Context,退出当前Activity后都会且会在延迟几秒钟后停止播放//0-6,通过一个资源ID:Context context, int resId, int prioritysoundIdList.add(soundPool.load(context, R.raw.s1_message, 0));soundIdList.add(soundPool.load(context, R.raw.s10_42kb, 0));soundIdList.add(soundPool.load(context, R.raw.caravan_15s_59kb, 0));soundIdList.add(soundPool.load(context, R.raw.s8_67kb, 0));soundIdList.add(soundPool.load(context, R.raw.ljsw_35s_68kb, 0));soundIdList.add(soundPool.load(context, R.raw.ljsw_49s_102kb, 0));soundIdList.add(soundPool.load(context, R.raw.hellow_tomorrow_6s_237kb, 0));//7,通过指定的路径:String path, int prioritysoundIdList.add(soundIdList.size(), 0);//如果文件不存在,则就不能set,否则会throw IndexOutOfBoundsExceptionString path = Environment.getExternalStorageDirectory() + File.separator + "caravan.mp3";soundIdList.set(soundIdList.size() - 1, soundPool.load(path, 0));//注意:add和set时传入的index是不一样的!//8-9,通过AssetFileDescriptor:AssetFileDescriptor afd, int prioritytry {soundIdList.add(soundIdList.size(), 0);//为防止异常后后续的代码执行不到导致index错乱,我们在一开始就直接add两个soundIdList.add(soundIdList.size(), 0);AssetFileDescriptor afd = getAssets().openFd("voice/caravan_15s_59kb.mp3");//openNonAssetFdsoundIdList.set(soundIdList.size() - 2, soundPool.load(afd, 0));//通过FileDescriptor:FileDescriptor fd, long offset, long length, int priorityFileDescriptor fd = afd.getFileDescriptor();long offset = afd.getStartOffset(), length = afd.getLength();Log.i("bqt", "【afd】offset=" + offset + ",length=" + length);//offset=40786180,length=60480soundIdList.set(soundIdList.size() - 1, soundPool.load(fd, offset + length / 2, length / 2, 0));} catch (IOException e) {e.printStackTrace();}//10soundIdList.add(soundPool.load(getResources().openRawResourceFd(R.raw.s1_global), 0));}@Overrideprotected void onDestroy() {super.onDestroy();soundPool.release();//释放所有资源}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {if (position <= 10) {int soundID = soundIdList.get(position);int loop = 0;//0 = no loop, -1 = loop foreverif (position == 0) loop = -1;else if (position == 1) loop = 2;//3次//播放指定soundID的音频:【int soundID】, float leftVolume, float rightVolume,int priority, 【int loop】, float rateint streamID = soundPool.play(soundID, 1.0f, 1.0f, 1, loop, 1.0f);Toast.makeText(this, "soundID=" + soundID + " streamID=" + streamID, Toast.LENGTH_SHORT).show();//指定streamID的参数进行设置,这些参数都可以在播放时指定soundPool.setLoop(streamID, 1);//实践证明,这里设置无效switch (position) {case 1:soundPool.setRate(streamID, 1.5f);//大小并没有限制,但是一般不要小于0.5,不要大于1.5,否则声音严重失真soundPool.setVolume(streamID, 1.0f, 0.1f);//只能降低,不能提高。The value must be in the range of 0.0 to 1.0break;case 2:soundPool.setRate(streamID, 0.5f);soundPool.setVolume(streamID, 0.1f, 1.0f);break;}} else {switch (position) {case 11:soundPool.autoPause();//可以多次调用,每次都是把当前正在播放的音乐暂停,并加入同一个列表中break;case 12:soundPool.autoResume();//将所有暂停的音乐从暂停位置重新开始播放break;case 13:Toast.makeText(this, "" + soundPool.unload(soundIdList.get(0)) + " " + soundPool.unload(soundIdList.get(1)), Toast.LENGTH_SHORT).show();//unload并不能停止正在播放的音乐,特别是loop=-1的,仍会循环播放break;case 14:soundPool.release();//会停止正在播放的所有音乐break;}}}}
SoundPool 音频播放 API 详解【示例】的更多相关文章
- MediaPlayer 状态机 API 详解 示例
简介 public class android.media.MediaPlayer extends Object implements VolumeAutomation 可能需要的权限: One ma ...
- FFmpeg编解码处理2-编解码API详解
本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10584925.html FFmpeg编解码处理系列笔记: [0]. FFmpeg时间戳详 ...
- 百度地图API详解之事件机制,function“闭包”解决for循环和监听器冲突的问题:
原文:百度地图API详解之事件机制,function"闭包"解决for循环和监听器冲突的问题: 百度地图API详解之事件机制 2011年07月26日 星期二 下午 04:06 和D ...
- 【Unity编程】Unity中关于四元数的API详解
本文为博主原创文章,欢迎转载,请保留出处:http://blog.csdn.net/andrewfan Unity中关于四元数的API详解 Quaternion类 Quaternion(四元数)用于计 ...
- SDN 网络系统之 Mininet 与 API 详解
SDN 网络系统之 Mininet 与 API 详解 Mininet 是轻量级的软件定义网络系统平台,同时提供了对 OpenFlow 协议的支持.本文主要介绍了 Mininet 的相关概念与特性,并列 ...
- 【HANA系列】SAP HANA XS的JavaScript API详解
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[HANA系列]SAP HANA XS的Java ...
- Java8学习笔记(五)--Stream API详解[转]
为什么需要 Stream Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念.它也不同于 StAX 对 ...
- DOM API详解
来源于:http://zxc0328.github.io/2016/01/23/learning-dom-part1/ https://zxc0328.github.io/2016/01/26/lea ...
- Lucene系列六:Lucene搜索详解(Lucene搜索流程详解、搜索核心API详解、基本查询详解、QueryParser详解)
一.搜索流程详解 1. 先看一下Lucene的架构图 由图可知搜索的过程如下: 用户输入搜索的关键字.对关键字进行分词.根据分词结果去索引库里面找到对应的文章id.根据文章id找到对应的文章 2. L ...
随机推荐
- JAVA单向链表实现
JAVA单向链表实现 单向链表 链表和数组一样是一种最常用的线性数据结构,两者各有优缺点.数组我们知道是在内存上的一块连续的空间构成,所以其元素访问可以通过下标进行,随机访问速度很快,但数组也有其缺点 ...
- 跟厂长学PHP7内核(一):发展史
PHP1 1994年,一位名叫Rasmus lerdorf的兄台为了在网上展示自己的履历和网页流量的统计,用Perl开发了一套脚本,后来因与日俱增的需求无法得到满足,lerdorf便使用c语言进行了重 ...
- 文件系统层级结构标准(FHS)
参考资料:FHS 简介 FHS目前发展到3.0版本,发布于2015年6月3日,由Linux基金会在负责维护.它规定了Linux的文件层级结构,使得各Linux发行版.软件开发商知道应该将哪些文件放在哪 ...
- Javascript中call方法和apply方法用法和区别
第一次在博客园上面写博客,知识因为看书的时候发现了一些有意思的知识,顺便查了一下资料,就发到博客上来了,希望对大家有点帮助. 连续几天阅读<javascript高级程序设计>这本书了,逐渐 ...
- Python进阶篇:文件系统的操作
通过一个例子来熟悉文件的基本操作:创建文件,读取文件,修改文件,删除文件,重命名文件,判断文件是否存在 ''' 编写可供查询的员工信息表--学号 姓名 年龄 班级 1. 提供格式化查询接口 2. 允许 ...
- Java设计模式GOF之工厂模式
一.工厂模式(Factory) 1.实现了创建者和调用者的分离 2.应用场景 ①JDK中 Calendar 的 getInstance(): ②JDBC 的 Connection 对象的获取: ③Hi ...
- 数据准备<5>:变量筛选-实战篇
在上一篇文章<数据准备<4>:变量筛选-理论篇>中,我们介绍了变量筛选的三种方法:基于经验的方法.基于统计的方法和基于机器学习的方法,本文将介绍后两种方法在Python(skl ...
- C# 微信小程序获取openid sessionkey
项目介绍 1.微信小程序获取openid和session_key 2.后台使用C#开发 项目流程 准备工作 1 获取appid 1.1 下载微信web开发工具 https://developers.w ...
- Tomcat启动异常 java.net.BindException: Cannot assign requested address: JVM_Bind
从Apache官网下载的tomcat7,在MyEclipse中启动时抛出如下异常: 严重: StandardServer.await: create[localhost:8005]: java.net ...
- 力特ZE398C驱动光盘-USB转RS232-支持Windows 10/Mac
这个工具是USB1.1的,相对来说比较老,一开始做小白鼠不知道买了USB1.1的,所以我不建议买这个,还有其它的型号,支持USB2.0和USB3.0,不过价格也相对来说比较贵,这个才30块钱左右. 关 ...