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);  

你可能感兴趣的:(Android开发)