MediaPlayer cant play audio files from program data folder?

后端 未结 5 1723
春和景丽
春和景丽 2021-02-15 18:11

When i record my audio from MIC and store file in /data/data/..... why MediaPlayer can\'t play this file ? If i change destination to / sdcard/..... - all works great. I do so

相关标签:
5条回答
  • 2021-02-15 18:44

    use MediaPlayer.setDataSource(FileDescriptor fd)

    0 讨论(0)
  • 2021-02-15 18:58

    Due to the Android security model, MediaPlayer haven't enough rights. It can access SD card, but can't access another places with out permissions.

    As so, setDataSource(...) can thrown SecurityException and I think it's happening.

    You can play this file next ways:

    • copy it to temp dir and play;
    • copy it to temp dir and play;
    • copy it to sdcard;
    • read it fully to memory and try play via stream.
    0 讨论(0)
  • 2021-02-15 18:59

    Try setting ContentValues and to store some standard meta-data properties. Then using a ContentResolver to set the meta-data and Uri to the file.

    see: http://developer.android.com/guide/topics/media/index.html

    "Example: Audio Capture Setup and Start", then try changing Uri base to your /data/data/-filename.

    0 讨论(0)
  • 2021-02-15 19:00

    Better practice is to close the stream, like this:

    FileInputStream stream = new FileInputStream(path);
    mediaPlayer.setDataSource(stream.getFD());
    stream.close();
    

    It is noted in the documentation of the method:

    android.media.MediaPlayer.setDataSource(FileDescriptor fd)

    Sets the data source (FileDescriptor) to use. It is the caller's responsibility to close the file descriptor. It is safe to do so as soon as this call returns.

    0 讨论(0)
  • 2021-02-15 19:01

    i had the same issues... whenever i used setDataSource with filepaths, it would not work; kept getting IOException.

    changing my code to use setDataSource(FileDescriptor) does work... and with this i don't have to copy the files to SDCard or anything like that.

    So, with a simple File object, create a new FileInputStream and pass the actual file descriptor as data source as in:

    setDataSource((new FileInputStream(myFileInstance)).getFD());
    

    creating an input stream pulls the file data into memory and thereby addresses /data/data access violations.

    0 讨论(0)
提交回复
热议问题