Playing music on Android

package moligamescr.pingpongthebeginner; //Import the libraries needed import android.media.MediaPlayer; import android.support.v7.app.ActionBarActivity; import java.util.Random; public class PingPong extends ActionBarActivity { //Create the object instance MediaPlayer private MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ping_pong); //Initialize the object mp this.mp = new MediaPlayer(); ////Call the method to play music initializeMusic(); } @Override protected void onPause() { super.onPause(); //If music is playing then pause if (mp.isPlaying()){ mp.pause(); } } @Override protected void onResume() { super.onResume(); //If music was playing then resume it mp.start(); } @Override protected void onStop() { super.onStop(); //If music is playing then stop and release the MediaPlayer if (mp.isPlaying()){ mp.stop(); mp.release(); } } //Method that playing the music by random public void initializeMusic() { //Create a new object Random Random r = new Random(); //Create a variable random from 1 to 9 int numberSongRandom = r.nextInt(9)+1; //Evaluate the variable numberSongRandom switch (numberSongRandom){ //For case 1 play the music named song01 and successively case 1: mp = MediaPlayer.create(PingPong.this, R.raw.song01); break; case 2: mp = MediaPlayer.create(PingPong.this, R.raw.song02); break; case 3: mp = MediaPlayer.create(PingPong.this, R.raw.song03); break; case 4: mp = MediaPlayer.create(PingPong.this, R.raw.song04); break; case 5: mp = MediaPlayer.create(PingPong.this, R.raw.song05); break; case 6: mp = MediaPlayer.create(PingPong.this, R.raw.song06); break; case 7: mp = MediaPlayer.create(PingPong.this, R.raw.song07); break; case 8: mp = MediaPlayer.create(PingPong.this, R.raw.song08); break; case 9: mp = MediaPlayer.create(PingPong.this, R.raw.song09); break; } //Initialize the MediaPlayer to play the music chosen mp.start(); } }
How to play music on Android with Java. I use Android Studio but that doesn't matter.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.