本文实例为大家分享了Android使用SoundPool播放音效的具体代码,供大家参考,具体内容如下
SoundPool (int, int streamType int maxStreams srcQuality)参数依次是:
①指定支持多少个声音,SoundPool对象中允许同时存在的最大流的数量。
②指定声音类型,流类型可以分为四种类型。在AudioManager中定义。
③指定声音品质(采样率变换质量),一般直接设置为0 !,
以下是对它的常用方法的介绍:
<强> 1。加载声音资源强>
加载(上下文语境、int渣油int优先)
负载(String路径,int优先)
负载(FileDescriptor fd、抵消长、长长度,int优先)
加载(AssetFileDescriptor发展署,int优先)
<强>参数介绍:强>
-
<李>背景:上下文李>
<李>渣油:资源id 李>
<李>优先:没什么用的一个参数,建议设置为1,保持和未来的兼容性李>
<李>路径:文件路径李>
<李> FileDescriptor:貌似是流吧,这个我也不知道李>
<李> AssetFileDescriptor:从资产目录读取某个资源文件,其用法:<强> 强> 李>
<强> 2。播放控制强>
玩(int soundID leftVolume浮动,浮动rightVolume, int优先,int循环,浮动利率)
参数依次是:
-
<李> soundID:负载()返回的声音ID号李>
<李> leftVolume:左声道音量设置李>
<李> rightVolume:右声道音量设置李>
<李>优先:指定播放声音的优先级,数值越高,优先级越大。李>
<李>循环:指定是否循环:1表示无限循环,0表示不循环,其他值表示要重复播放的次数李>
<李>率:指定播放速率:1.0的播放率可以使声音按照其原始频率,而2.0的播放速率,可以使声音按照其原始频率的两倍播放。如果为0.5的播放率,则播放速率是原始频率的一半。播放速率的取值范围是0.5至2.0。
李>
<强> 3。资源释放强>
方法:可以通过释放()方法释放所有SoundPool对象所占据的内存和资源,也可以根据声音ID来释放。
下面是使用SoundPool实现的一个代码示例:
1只,运行效果图:
2只;MainActivity代码:
进口android.content.res.AssetManager; 进口android.media.AudioManager; 进口android.media.SoundPool; 进口android.os.Bundle; 进口android.support.v7.app.AppCompatActivity; 进口android.view.View; 进口android.widget.Button; 进口java.util.HashMap; 公共类MainActivity AppCompatActivity延伸实现View.OnClickListener { 私人按钮btnOne; 私人按钮btnTwo; 私人按钮btnThree; 私人按钮btnFour; 私人按钮btnFive; 私人按钮btn_release; 私人AssetManager管理者; 私人SoundPool mSoundPool=零; 私人HashMap<整数,Integer>soundID=new HashMap<整数,Integer> (); @Override 保护空白> & lt; LinearLayout xmlns: android=" http://schemas.android.com/apk/res/android " xmlns:工具=" http://schemas.android.com/tools " android: layout_width=" match_parent " android: layout_height=" match_parent " android:取向=按怪薄? 工具:上下文=?MainActivity”比; & lt;按钮 android: id=癅 + id/btn_play1” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="声音1 "/比; & lt;按钮 android: id=癅 + id/btn_play2” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="声音2”/比; & lt;按钮 android: id=癅 + id/btn_play3” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="声音3”/比; & lt;按钮 android: id=癅 + id/btn_play4” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="声音4”/比; & lt;按钮 android: id=癅 + id/btn_play5” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="声音5”/比; & lt;按钮 android: id=癅 + id/btn_release” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="释放SoundPool”/比; & lt;/LinearLayout>Android使用SoundPool播放音效