Media Player設置播放資源時要注意的問題

用MediaPlayer加載播放資源的時候一直遇到(-38,0), 仔細看了終於發現了問題所在,由於要加載/data/data/<packageName>/下面的文件,我用了MediaPlayer.setDataSource(String path)這個方法,原來API裏已經明確提到,這個文件有可能會被其餘process而不是調用的application使用,因此必需要是全局可訪問的外部文件,放在/data/data/<packageName>/下面,就不行了。官方說明以下java

When path refers to a local file, the file may actually be opened by a process other than the calling application. This implies that the pathname should be an absolute path (as any other process runs with unspecified current working directory), and that the pathname should reference a world-readable file. As an alternative, the application could first open the file for reading, and then use the file descriptor form setDataSource(FileDescriptor).app

因此更改成其餘方法,spa

FileInputStream fileInputStream = new FileInputStream(filePath);
mMediaPlayer.setDataSource(fileInputStream.getFD());

這樣就能夠了。code

另外,若是加載文件爲asset下面的,能夠用以下代碼設置:orm

AssetFileDescriptor afd = mParentActivity.getAssets() .openFd(filename);
mMediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
相關文章
相關標籤/搜索