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);  
  • 17
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值