How to play an audio d开发者_JS百科uring splash screen. Guidance needed.
My way to do this (no external sound needed, since I put my soundfile in my resources-folder):
In onCreate:
mp = MediaPlayer.create(getBaseContext(), R.raw.sound); /*Gets your
soundfile from res/raw/sound.ogg */
mp.start(); //Starts your sound
//Continue with your run/thread-code here
Remember to have the sound in .ogg-format; it's fully supported in Android.
An important thing below about handling the sound when the Splash Screen activity is stopped:
There are two general ways to manage the Splash Screen (and the sound inside it) when it's stopped:
Destroy the whole activity:
protected void onStop() { super.onStop(); ur.removeCallbacks(myRunnable); /*If the application is stopped; remove the callback, so the next time the application starts it shows the Splash Screen again, and also, so the thread-code, don't continue after the application has stopped */ finish(); onDestroy(); }
Or you can just stop the sound in onStop:
protected void onStop() { super.onStop(); if(mp.isPlaying()){ //Must check if it's playing, otherwise it may be a NPE mp.pause(); //Pauses the sound ur.removeCallbacks(myRunnable); } }
If you choose the second alternative you also have to start your Callback and MediaPlayer in the onStart-method.
I prefer the first alternative.
You can play audio files using the MediaPlayer class.
Example
MediaPlayer player = new MediaPlayer();
player.setDataSource("/sdcard/audiotrack.mp3");
player.prepare();
player.start();
精彩评论