简体   繁体   中英

Android studio how to play background music automatically when activity started

Can anyone help me with my problem, i am trying to play a background music automatically without a button when activity started.

I dont have any idea how.

Add music file in the raw folder then call R.raw.[musincname] then call function in your onCreate or onStart,....

public static void PlayVoice(final Context context, int rawVoice) {
    voice = MediaPlayer.create(context, rawVoice);
    voice.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            if (voice != null) {
                voice.release();
            }
        }
    });
    voice.start();
}
 public void audioPlayer(String path, String fileName){
//set up MediaPlayer    
MediaPlayer mp = new MediaPlayer();

try {
    mp.setDataSource(path + File.separator + fileName);
    mp.prepare();
    mp.start();
} catch (Exception e) {
    e.printStackTrace();
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM