majestyc54
majestyc54

Reputation: 125

android play music on opening app

I want to make an app for my mom's birthday which is tomorrow that displays a happy birthday message(already got that taken care of) and plays the happy birthday song when the app is opened. I'm a complete noob to android programming and don't know anything more than basic xml but I want to get this done. Can you guys please show me how what code to use to play a song on opening the app without any more input from the user?

Upvotes: 0

Views: 4701

Answers (3)

Pravin Fofariya
Pravin Fofariya

Reputation: 346

Try this 

If you want to play song when the app is opened then do following step
step 1. First create the folder named raw in res/ directory.
step 2. Put your birthday song in raw directory in you project.

Then write below code in you activity.


   class Playsong extends Activity {

    MediaPlayer mPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPlayer= MediaPlayer.create(getApplicationContext(), R.raw.songname);
        mPlayer.start();
    }

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

    }
   }

Upvotes: 1

ak sacha
ak sacha

Reputation: 2179

First create the folder named raw in res/ directory and put your song in raw folder.

write the below code in onCreate()

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();

    }
}

Upvotes: 5

Android Geek
Android Geek

Reputation: 9225

First of all put the song file in raw folder under res folder. After that in your activity:

public static MediaPlayer splashSound;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    splashSound = MediaPlayer.create(SplashScreen.this, R.raw.start_music);
    splashSound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer splashSound) {
            splashSound.stop();
            splashSound.release();
        });

Upvotes: 0

Related Questions