首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

android使用MediaPlayer播放音乐文件时遇到的有关问题

2012-07-28 
android使用MediaPlayer播放音乐文件时遇到的问题把mp3文件放在Assets文件夹里,然后用MediaPlayer.setData

android使用MediaPlayer播放音乐文件时遇到的问题

把mp3文件放在Assets文件夹里,然后用MediaPlayer.setDataSource(FileDescriptor fd)来设置数据源,然后再调用MediaPlayer.prepare();结果报错了:
ERROR/PlayerDriver(30): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported
在网上找解决办法,看到大部分的建议是换create(Context context, int resid)来创建一个MediaPlayer,试了一下果然成功,但这是为什么呢?
后来只好查看android的源码,发现MediaPlayer.setDataSource(FileDescriptor fd)是这样实现的:
? ? public void setDataSource(FileDescriptor fd)
? ?? ?? ?? ?throws IOException, IllegalArgumentException, IllegalStateException {
? ?? ???// intentionally less than LONG_MAX
? ?? ???setDataSource(fd, 0, 0x7ffffffffffffffL);
? ? }
其实就是调用了void setDataSource(FileDescriptor fd, long offset, long length)这个函数。
后来我在调式的时候发现,AssetFileDescriptord的offset并不为0。于是改为乖乖的使用setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
然后成功了。

?

我这样,但忘了关afd.close();//结果没有声音,悲剧,还有 mMediaPlayer.reset();要重置不然再播放会报错

public void playMusic(String mediaName) {
??? ??? try {

??? ??? ??? /* 重置MediaPlayer */
??? ??? ??? mMediaPlayer.reset();
??? ??? ???

??? ??? ??? String path="mp3/"+mediaName+".mp3";??? ??? ???
//??? ??? ??? /* 设置要播放的文件的路径 */
??? ??? ??? AssetFileDescriptor afd = context.getAssets().openFd(path);
??? ??? ??? mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());??? ???
??? ??? ??? afd.close();
??? ??? ???
??? ??? ??? mMediaPlayer.prepare();
??? ??? ??? mMediaPlayer.start();???
??? ??? ???
??? ??? }? catch (IOException ex) {
??????????? Log.d(TAG, "create failed:", ex);
??????????? // fall through
??????? } catch (IllegalArgumentException ex) {
??????????? Log.d(TAG, "create failed:", ex);
?????????? // fall through
??????? } catch (SecurityException ex) {
??????????? Log.d(TAG, "create failed:", ex);
??????????? // fall through
??????? }
??? }

热点排行