1. 程式人生 > >Android中MediaPlayer的setDataSource方法的使用

Android中MediaPlayer的setDataSource方法的使用

MediaPlayer.java檔案路徑:frameworks/base/media/java/android/media/MediaPlayer.java

MediaPlayer的setDataSource()方法主要有四種:

Sets the data source as a content Uri.
@param context the Context to use when resolving the Uri
@param uri the Content URI of the data you want to play
public void setDataSource(Context context, Uri uri)

Sets the data source (file-path or http/rtsp URL) to use.
@param path the path of the file, or the http/rtsp URL of the stream you want to play
public void setDataSource(String path)

Sets the data source (FileDescriptor) to use. It is the caller’s responsibility
to close the file descriptor. It is safe to do so as soon as this call returns.
@param fd the FileDescriptor for the file you want to play
public void setDataSource(FileDescriptor fd)

Sets the data source (FileDescriptor) to use. The FileDescriptor must be
seekable (N.B. a LocalSocket is not seekable). It is the caller’s responsibility
to close the file descriptor. It is safe to do so as soon as this call returns.
@param fd the FileDescriptor for the file you want to play
@param offset the offset into the file where the data to be played starts, in bytes
@param length the length in bytes of the data to be played
public void setDataSource(FileDescriptor fd, long offset, long length)

1. 播放應用的資原始檔

1. 直接呼叫create函式例項化一個MediaPlayer物件,播放位於res/raw/test.mp3檔案
MediaPlayer  mMediaPlayer = MediaPlayer.create(this, R.raw.test);2. test.mp3放在res/raw/目錄下,使用setDataSource(Context context, Uri uri)
mp = new MediaPlayer(); 
Uri setDataSourceuri = Uri.parse("android.resource://com.android.sim/"+R.raw.test);
mp.setDataSource(this, uri);

說明:此種方法是通過res轉換成uri然後呼叫setDataSource()方法,需要注意格式Uri.parse("android.resource://[應用程式包名Application package name]/"+R.raw.播放檔名);
例子中的包名為com.android.sim,播放檔名為:test;特別注意包名後的"/"。3. test.mp3檔案放在assets目錄下,使用setDataSource(FileDescriptor fd, long offset, long length)
AssetManager assetMg = this.getApplicationContext().getAssets();
AssetFileDescriptor fileDescriptor = assetMg.openFd("test.mp3");  
mp.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength()); 

2. 播放儲存裝置的資原始檔

MediaPlayer mediaPlayer = new MediaPlayer();  
mediaPlayer.setDataSource("/mnt/sdcard/test.mp3");

3. 播放遠端的資原始檔

Uri uri = Uri.parse("http://**");  
MediaPlayer mediaPlayer = new MediaPlayer(); 
mediaPlayer.setDataSource(Context, uri);