Android Sound无法在启动画面中播放

时间:2013-03-09 19:08:38

标签: java android audio

在启动画面显示时播放声音时遇到麻烦。我在“res”目录下创建了“raw”目录,并将droid.mp3文件放在那里(大约150Kb)。

这是负责启动画面外观和声音的java文件的代码:

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;

public class SplashActivity extends Activity 
{
    public  MediaPlayer splashSound;

    protected void onCreate(Bundle splashBundle) 
    {
        super.onCreate(splashBundle);
        setContentView(R.layout.splash);
        splashSound = MediaPlayer.create(SplashActivity.this, R.raw.droid);
        Thread t1 = new Thread() {
            public void run() {
                try 
                {
                    sleep(5000);
                } 
                catch (InterruptedException IE)
                {
                    IE.printStackTrace();
                } 
                finally 
                {
                    Intent mainActivityIntent=new Intent("com.example.stamapp.MAINACTIVITY");
                    startActivity(mainActivityIntent);
                }
            }
        };
        t1.start();
    }

    @Override
    protected void onPause() {

        super.onPause();
        splashSound.release();
        finish();
    }

}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

而不是Thread尝试使用Handler.postDelayed作为:

 Handler handler;
protected void onCreate(Bundle splashBundle) 
    {
        super.onCreate(splashBundle);
        setContentView(R.layout.splash);
        handler = new Handler();  
        splashSound = MediaPlayer.create(SplashActivity.this, 
                                            R.raw.droid);   
        splashSound.start();  //<<<play sound on Splash Screen
        handler.postDelayed(runnable, 5000);
    }
private Runnable runnable = new Runnable() {
   @Override
   public void run() {
     //start your Next Activity here
   }
};

,第二种方法是将MediaPlayer.setOnCompletionListener添加到MediaPlayer实例,该实例在完成媒体源播放时调用,而不将5000延迟视为:

protected void onCreate(Bundle splashBundle) 
        {
            super.onCreate(splashBundle);
            setContentView(R.layout.splash);

            splashSound = MediaPlayer.create(SplashActivity.this, 
                                                R.raw.droid);   
            splashSound.setOnCompletionListener(new 
                              MediaPlayer.OnCompletionListener() {
           @Override
            public void onCompletion(MediaPlayer splashSound) {

             splashSound.stop();
             splashSound.release();
                   //start your Next Activity here
           }
        });
        splashSound.start();  //<<<play sound on Splash Screen
   }