以Switch按钮为例
先声明三个对象
private Switch aSwitch_sound;private SoundPool soundPool;//音频通知声音播放器private int soundID;//音频资源ID
添加两个方法
@SuppressLint("NewApi")private void initSound() {soundPool = new SoundPool.Builder().build();soundID = soundPool.load(this, R.raw.qipao, 1);}//实例化soundPool和soundID R.raw.qipao为音频资源位置
private void playSound() {soundPool.play(soundID,0.1f,//左耳道音量【0~1】0.5f,//右耳道音量【0~1】0, //播放优先级【0表示最低优先级】0, //循环模式【0表示循环一次,-1表示一直循环,其他表示数字+1表示当前数字对应的循环次数】1//播放速度【1是正常,范围从0~2】);}
附上完整代码
public class SetActivity extends AppCompatActivity {private Switch aSwitch_sound;//switch按钮private SoundPool soundPool;//音频通知声音播放器private int soundID;//音频资源ID@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_set);initSound();aSwitch_sound=findViewById(R.id.switch_sound);aSwitch_sound.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {playSound();}});}@SuppressLint("NewApi")private void initSound() {soundPool = new SoundPool.Builder().build();//实例化音频通知播放器soundID = soundPool.load(this, R.raw.qipao, 1);//设置资源ID}private void playSound() {soundPool.play(soundID,0.1f,//左耳道音量【0~1】0.5f,//右耳道音量【0~1】0, //播放优先级【0表示最低优先级】0, //循环模式【0表示循环一次,-1表示一直循环,其他表示数字+1表示当前数字对应的循环次数】1//播放速度【1是正常,范围从0~2】);}}