1. Apk内,预定义按键与触发按键:
layout 按键定义:
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="start"/>
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="false"/>
按键触发,代码处理:
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
playSound(1,3);
break;
case R.id.pause:
mSoundpool.pause(1);
mSoundpool.stop(1);
break;
default:
break;
}
}
2. 创建SoundPool对象,与启动停止播放:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initSp();
start = (Button) findViewById(R.id.start);
pause = (Button) findViewById(R.id.pause);
start.setOnClickListener(this);
pause.setOnClickListener(this);
}
private void initSp() { // 初始化 mSoundpool
if (Build.VERSION.SDK_INT >= 21) {
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(1);
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
builder.setAudioAttributes(attrBuilder.build());
mSoundpool = builder.build();
} else {
mSoundpool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
}
map = new HashMap();
// 加载资源文件
map.put(1, mSoundpool.load(this, R.raw.008, 1));
}
// 进行播放
private void playSound(int sound, int number) {
mSoundpool.play( sound,
1, // leftVolume
1, // rightVolume
1, // priority
number, // loop
(float)1);// rate,1为正常速度
}
3. 按照,如上最简步骤进行调试,即可通过Soundpool类对象Api进行音频播放测试。
标签:pause,layout,音频,SoundPool,start,mSoundpool,android,id From: https://blog.csdn.net/xuann/article/details/140859457