MediaPlayer setDataSource, better to use path or FileDescriptor?

Actually, it turns out that there IS a difference in certain situations.

mediaPlayer.setDataSource(String path) will fail when you call mediaPlayer.prepare(), if you are trying to load a file from getApplicationContext().getFilesDir(), depending on how the file was saved. For example, if I write a file using new RandomAccessFile(filePath, "rw"), the file is not actually readable by the mediaplayer if you use mediaPlayer.setDataSource(String path). The prepare() will immediately trigger error(1, -2147483648) from the mediaplayer; essentially a file permission error. SDK 9 introduced file.setReadable (boolean readable, boolean ownerOnly) which would presumably allow you to resolve this issue by setting ownerOnly to false…but that doesn’t help you if you need to support older SDKs.

HOWEVER, mediaPlayer.setDataSource(FileDescriptor fd) does NOT have this problem and mediaplayer will successfully prepare the same exact file without a permission problem.

Leave a Comment