Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

android - MediaPlayer setDataSource, better to use path or FileDescriptor?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...