2013-01-19 252 views

回答

1
Intent intent = new Intent(android.content.Intent.ACTION_VIEW); 

Uri data = Uri.parse("file://"+Environment.getExternalStorageDirectory() 
     .getAbsolutePath()+"/" + fileName); 
String type = "audio/mp3"; 
intent.setDataAndType(data, type); 
startActivity(intent); 

fileName是音頻的名字寫在你SDCard

+1

如果這些文件位於Project的原始文件夾中,該怎麼辦? –

+0

如果它們位於原始文件夾中,請指定該文件的路徑,例如fileName =「/com.package/data/media/audio/song.mp3」。或者路徑是什麼。 – Naskov

+1

我試過你的方式,但應用程序崩潰與「ActivityNotFoundException」..沒有發現活動處理意圖.... –

1

首先聲明MediaPlayer對象:

MediaPlayer mSoundPlayer; 

添加此功能:

//Play music 
    public void playSound(int id){ 
      try{ 
       mSoundPlayer = MediaPlayer.create(mContext, id); 
       mSoundPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 
        @Override 
        public void onPrepared(MediaPlayer arg0) { 
         mSoundPlayer.start(); 

        } 

       }); 
       mSoundPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 

        @Override 
        public void onCompletion(MediaPlayer mp) { 
         // TODO Auto-generated method stub 
         mSoundPlayer.release(); 
        }}); 
      } 
      catch (Exception e) { 
       // TODO: handle exception 
       Log.v("Sound Exception","Sound Exception = "+e.getMessage()); 
      } 
    } 

電話本:

playSound(R.raw.sound1); 

這將是一個很好的做法,釋放MediaPlayer

@Override 
    public void onPause(){ 
     super.onPause(); 
     if(mSoundPlayer!=null) 
      mSoundPlayer.release(); 
    } 

謝謝。

+0

我希望通過點擊按鈕,音頻文件在Android的音樂播放器應用程序中啓動。通過這個程序,它在後臺運行,我將不得不創建播放/暫停/停止等按鈕。 –

+0

@ user1951199好吧我以爲你想在後臺玩。反正你的問題解決了? –

1

下面是示例代碼片段...

For playing audio files in android

Playing audio

public void splashPlayer() { 
VideoView videoHolder = new VideoView(this); 
setContentView(videoHolder); 
Uri video = Uri.parse("android.resource://" + getPackageName() + "/" 
    + R.raw.splash); 
videoHolder.setVideoURI(video); 
videoHolder.setOnCompletionListener(new OnCompletionListener() { 
    public void onCompletion(MediaPlayer mp) { 
    jumpMain(); //jump to the next Activity 
    } 
}); 
videoHolder.start(); 
} 

對於完整的教程去this

1

我試過這段代碼: -

button.setOnClickListener(new OnClickListener() 
{ 

@Override 
public void onClick(View v) 
{ 
Uri uri = Uri.parse("R.raw.fashion.mp3");//the audio file 
Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(intent); 

} 
}); 

但是,當我運行此代碼;該應用程序崩潰,LogCat顯示:「ActivityNotFoundException」...找不到處理意圖的活動。

-1

試試這個可能會有幫助。

Uri data = Uri.parse("file://"+Environment.getExternalStorageDirectory() 
       .getAbsolutePath()+"/" + audioName); 
     Intent intent = new Intent(android.content.Intent.ACTION_VIEW, data); 

     String type = "audio/mp3"; 
     intent.setDataAndType(data, type); 
     startActivity(intent); 
+0

問題要求播放來自res/raw目錄的音頻,並且您正在使用外部存儲器進行應答。 – Manpreet