我在启动画面上添加了一个5秒的声音mp3到我的应用程序,但是在加载应用程序时它的播放波动,我需要做些什么才能顺利播放?
public class Splash extends Activity{
MediaPlayer ourSong;
@Override
protected void onCreate(Bundle TravisLoveBacon) {
// TODO Auto-generated method stub
super.onCreate(TravisLoveBacon);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.onkar);
ourSong.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(4000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openStartingPoint = new Intent("com.sport.sport.MAINLAUNCHER2");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSong.release();
finish();
}
}
答案 0 :(得分:1)
你需要做些什么才能顺利进行游戏?更多的CPU,特别是在UI-Thread中。 (好吧,开个玩笑: - )
您可以使用SoundPool
并在播放之前预加载歌曲。 SoundPool特别适用于游戏等中的短音。
这是加载播放某些音乐的最短代码。请记住在AsyncTask
中运行它。它可能需要半秒才能开始,但它可以毫无问题地运行。
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if(status == 0) soundPool.play(sampleId, 1f, 1f, Integer.MAX_VALUE, 0, 1f);
}
});
try {
soundId = soundPool.load(getAssets().openFd(file), 1);
} catch (IOException e) {
Log.e("TAG", e.getMessage(), e);
return;
}
至少需要API级别8并将音量用于音乐。
我在您的代码中看到的另外两件事:
startActivity
做的?那部分不起作用。答案 1 :(得分:0)
以下是我将如何构建一个带有声音的启动画面。
这已经很长了,所以让我就此发表一些评论。
Semaphore
和aquire
中的doInBackground
以及release()
末尾的onLoadComplete()
}。就是这样。没有大量测试,但希望你可以使用它的起点:
public class Splash extends Activity {
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.splash);
/*
* I would finish here, to give
* Android some time for layout
* and other things
*/
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
/*
* Now start background task
* There was a discussion about
* Splash screen some time ago.
* Especially when you should do the
* startActivity and what flags you
* should use in the Intent.
*/
// Start playing sound asynchronously
// R.raw.onkar
new AsyncTask<Void, Void, Void>() {
private SoundPool soundPool = new SoundPool(
1, AudioManager.STREAM_MUSIC, 0);
@Override
protected Void doInBackground(Void... params) {
// Put in here the code I've already posted!
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
soundPool.release();
Intent openStartingPoint = new Intent(
"com.sport.sport.MAINLAUNCHER2");
startActivity(openStartingPoint);
/*
* Actually, you can start the next activity here
* or from onResume method with postDelayed(...)
* This way here ensures that the Activity is
* started right after the sound was played.
*/
}
}.execute((Void) null);
}
}