2010-07-30 29 views

回答

7

我的方式做到這一點(不需要外部的聲音,因爲我把我的音效檔在我的資源文件夾):

在的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 

記住以.ogg格式發聲;它在Android中完全受支持。

低於開機畫面活動停止處理聲音的一個重要的事情:

有管理的閃屏(和它裏面的聲音)兩種常規方法,當它停止:

  1. 摧毀整個活動:

    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(); 
    } 
    
  2. 或者你可以只停留在S ound中的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); 
        } 
    } 
    

如果你選擇,你也不得不開始回調和MediaPlayer的在在onStart-方法的第二個選擇。

寧願第一個選擇。

+0

需要注意的是,在Android 2.2用戶之前,只有有限的內存才能保存應用程序。因此,最好將它們存儲在外部存儲器中。如果你有一些小型的聲音文件,這並不重要 - 但如果你有很多的話。 – Charles 2010-07-31 10:09:45

2

您可以使用MediaPlayer類播放音頻文件。

MediaPlayer player = new MediaPlayer(); 
player.setDataSource("/sdcard/audiotrack.mp3"); 
player.prepare(); 
player.start(); 
+0

可以更詳細地指定PLZ。 做你的一些代碼片段? 關於 – iscavengers 2010-07-30 10:01:24

+0

用一些代碼更新了我的文章。 – Charles 2010-07-30 12:17:11