资源准备:
视图代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2SoundActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="播放"
android:id="@+id/btn_play1" />
</LinearLayout>
java代码:
package com.example.androidmedia26;
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.HashMap;
import java.util.Map;
public class MainActivity2SoundActivity extends AppCompatActivity {
private Button btn;
private SoundPool soundPool;
private int index = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2_sound);
btn = findViewById(R.id.btn_play1);
AudioAttributes audioAttributes = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
soundPool = new SoundPool.Builder().setAudioAttributes(audioAttributes).build();
}else {
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
}
Map<Integer, Integer> musicId = new HashMap<>();
musicId.put(1, soundPool.load(this, R.raw.yx1, 1));
musicId.put(2, soundPool.load(this, R.raw.yx2, 1));
musicId.put(3, soundPool.load(this, R.raw.yx3, 1));
musicId.put(4, soundPool.load(this, R.raw.yx4, 1));
musicId.put(5, soundPool.load(this, R.raw.yx5, 1));
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (btn.getText().equals("播放")) {
btn.setText("下一个");
}
soundPool.play(musicId.get(index % 5 + 1), 1, 1, 0, 0, 1);
index++;
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
soundPool.release();
}
}
效果: