Let’s say I have a full path to a file. Which is the better approach to loading that file into a MediaPlayer?
String filePath = "somepath/somefile.mp3";
mediaPlayer.setDataSource(filePath);
OR
String filePath = "somepath/somefile.mp3";
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
mediaPlayer.setDataSource(inputStream.getFD());
inputStream.close();
Does it matter? Simply using the path seems easier but is there a reason to do the extra work to use a FileDescriptor?
Actually, it turns out that there IS a difference in certain situations.
mediaPlayer.setDataSource(String path)will fail when you callmediaPlayer.prepare(), if you are trying to load a file fromgetApplicationContext().getFilesDir(), depending on how the file was saved. For example, if I write a file usingnew RandomAccessFile(filePath, "rw"), the file is not actually readable by the mediaplayer if you usemediaPlayer.setDataSource(String path). Theprepare()will immediately triggererror(1, -2147483648)from the mediaplayer; essentially a file permission error. SDK 9 introducedfile.setReadable (boolean readable, boolean ownerOnly)which would presumably allow you to resolve this issue by settingownerOnlyto 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.