Android 自动播放音频 / Android auto play audio

Android 自动播放音频 / Android auto play audio

Prepare: make a folder called raw.
Right click res document -> new directory -> type res -> OK

Simply drag audio files into this folder.

Initialize MediaPlayer by: MediaPlayer mediaPlayer

Point the specific audio to this mediaPlayer: mediaPlayer = MediaPlayer.create(this, R.raw.[*your audio name here*]);

Play the audio: mediaPlayer.start();

If you want to auto play in when app starts, you need to write in onCreate function.

Sample:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
playAudio();
}

private void playAudio() {
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(this, R.raw.test_audio_1);

if (!mediaPlayer.isPlaying()) mediaPlayer.start();
else if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.start();
}
}//end playAudio

在Res文件夹下创建 raw文件夹.
右键 res 文件夹 -> 新建文件夹 -> 输入 raw -> OK

然后把音频文件拖入该文件夹下面

初始化MediaPlayer: MediaPlayer mediaPlayer

绑定播放音频: mediaPlayer = MediaPlayer.create(this, R.raw.[*your audio name here*]);

播放音频: mediaPlayer.start();

如果想app打开自动播放该app,需要在onCreate方法下触发该方法

举例:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
playAudio();
}

private void playAudio() {
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(this, R.raw.test_audio_1);

if (!mediaPlayer.isPlaying()) mediaPlayer.start();
else if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.start();
}
}//end playAudio

Enjoy coding!