Android 播放raw資料夾下音訊檔案

meixi_android&java發表於2018-12-06

1、複製音訊檔案到raw資料夾下

 

2、例項化音訊檔案

 

private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() { // 聲音
    public void onCompletion(MediaPlayer mediaPlayer) {
        mediaPlayer.seekTo(0);
    }
};
private static final float BEEP_VOLUME = 9.10f;
private MediaPlayer mediaPlayer;
private void initBeepSound() {
    if ( mediaPlayer == null) {
        // The volume on STREAM_SYSTEM is not adjustable, and users found it
        // too loud,
        // so we now play on the music stream.

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(beepListener);

        AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.sou);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            file.close();
            mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayer.prepare();
        } catch (IOException e) {
            mediaPlayer = null;
        }
    }
}

 

3、開始播放

mediaPlayer.start();

相關文章