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

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

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

    Simply drag audio files into this folder.

  2. Initialize MediaPlayer by: MediaPlayer mediaPlayer

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

  4. Play the audio: mediaPlayer.start();

  5. 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



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

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

  2. 初始化MediaPlayer: MediaPlayer mediaPlayer

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

  4. 播放音频: mediaPlayer.start();

  5. 如果想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!

你可能感兴趣的:(Android)