Media Player设置播放资源时要注意的问题

用MediaPlayer加载播放资源的时候一直遇到(-38,0), 仔细看了终于发现了问题所在,因为要加载/data/data/<packageName>/下面的文件,我用了MediaPlayer.setDataSource(String path)这个方法,原来API里已经明确提到,这个文件有可能会被其他process而不是调用的application使用,所以必须要是全局可访问的外部文件,放在/data/data/<packageName>/下面,就不行了。官方说明如下

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

所以更改为其他方法,

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

这样就可以了。

另外,如果加载文件为asset下面的,可以用如下代码设置:

AssetFileDescriptor afd = mParentActivity.getAssets() .openFd(filename);
mMediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();


你可能感兴趣的:(Media Player设置播放资源时要注意的问题)