您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
69_soundpool的使用
发布时间:2021-03-11 10:44:33编辑:雪饮阅读()
SoundPool —— 适合短促且对反应速度比较高的情况(游戏音效或按键声等)
这里加载一个shoot打枪的声音效果
建立布局文件activity_main.xml将shoot按钮加上:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="shoot"
android:onClick="shoot"
/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="shoot"
android:onClick="shoot"
/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
然后是主程序MainActivity.java的实现:
package com.example.soundpool;
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
int soundid;
SoundPool pool;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建一个声音池
//三个参数
//maxStream —— 同时播放的流的最大数量
//streamType —— 流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出)
//srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值
pool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
// 这语句代码是一个异步的操作,所以要一开始就放在onCreate处,等用户开始点击按钮的时候已经加载好了
//上下文,资源,优先级
soundid = pool.load(this, R.raw.ring, 1);
}
public void shoot(View view){
//参数leftVolume,rightVolume,priority,loop,rate
// 这里将左右声道都开到最大即1.0
// priority —— 流的优先级,值越大优先级高,影响当同时播放数量超出了最大支持数时SoundPool对该流的处理;
//loop —— 循环播放的次数,0为值播放一次,-1为无限循环,其他值为播放loop+1次(例如,3为一共播放4次).
//rate —— 播放的速率,范围0.5-2.0(0.5为一半速率,1.0为正常速率,2.0为两倍速率)
pool.play(soundid, 1.0f, 1.0f, 0, 0, 1.0f);
// taking tom
}
}
然后建立如raw目录于res目录中,然后在raw目录中放入枪的音效文件
最后部署项目到设备中即可通过shoot按钮点击发出枪的射击声音,由于文件是在项目中的资源目录中,所以并不需要之前那样读取文件还需要加一个外部存储权限于清单文件中,并且还需要用户勾选才行。
关键字词:soundpool,声音池,android