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
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值