在Android中,SoundPool是用于播放音頻的一種類(lèi)
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
import android.media.AudioManager;
import android.media.SoundPool;
public class MainActivity extends AppCompatActivity {
private SoundPool soundPool;
private int soundId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化SoundPool
initSoundPool();
}
private void initSoundPool() {
// 設(shè)置最大音頻流數(shù)量和音頻優(yōu)先級(jí)
int maxStreams = 1;
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
if (audioManager != null) {
maxStreams = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}
soundPool = new SoundPool.Builder().setMaxStreams(maxStreams).build();
// 加載音頻資源
soundId = soundPool.load(this, R.raw.your_sound_file, 1);
}
}
請(qǐng)將R.raw.your_sound_file
替換為您要加載的音頻文件的資源ID。
soundPool.play()
方法:soundPool.play(soundId, 1, 1, 0, 0, 1);
onDestroy()
方法中,釋放SoundPool資源:@Override
protected void onDestroy() {
super.onDestroy();
if (soundPool != null) {
soundPool.release();
soundPool = null;
}
}
這樣,您就成功地初始化了SoundPool并播放了音頻。請(qǐng)注意,SoundPool適用于播放短音頻,如按鈕點(diǎn)擊聲等。對(duì)于長(zhǎng)時(shí)間播放的音頻,建議使用MediaPlayer。