How to Play Music in Android Studio?

32,380

Solution 1

You need to put your .mp3 file in /res/raw for this to work! (Just create a new folder named "raw" in /res)

Write this in your OnCreate() in your MainActivity:

class song extends Activity {
MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.yoursong);

    mediaPlayer.start();

}

@Override
protected void onPause() {
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();

}

}

Solution 2

In addition to Daniels answer, I'd move the mediaPlayer.start() to onResume() in the Activity. That way, the song starts playing if you put your device on standby and turn it back on.

(I need 50 reputation to comment, so I'm sorry I couldn't do it like that ^^')

Share:
32,380
J patel
Author by

J patel

Updated on July 09, 2022

Comments

  • J patel
    J patel almost 2 years

    Okay, So I am Making an app called Fall Down 4 in Android Studio. Now, I need to know if there is any way I can play music once I run my app.

    I know how to start a music once you click on a certain button but that's not what I want. What i want to know if if there is any way that When I run my app, It just starts playing the music.

    For Example: Many of the Games have music playing at the back when you run and then u have option in settings to turn it off. One Game Would be Fall Down Delux where the Music Keeps playing until I press the Turn Off Button.

    So Please let me know if there is any way that I could do what I have explained above.

    Thank You.