As example the following code illustrate storing audio file:
FileOutputStream outStream = null; String filename = null; // some code ... outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
Please note that we use MODE_PRIVATE disallowing other 3rd party apps to access your application data.
To play audio we call the following:
Context context = null; String filename = null; //some code ... MediaPlayer mediaPlayer = new MediaPlayer(); File file = getContext().getFileStreamPath(filename); Uri uri = Uri.fromFile(file); mediaPlayer.setDataSource(context, uri); mediaPlayer.prepare();
On my devices with Android 4.0+ it works just fine but on Android 2.3.3 an error is thrown.
In example above MediaPlayer is trying to access your application file space itself, which is not allowed because of MODE_PRIVATE.
To solve this problem we could easily set MODE_WORLD_READABLE but this mode is deprecated since API 17 and it is highly insecure. In that case not only MediaPlayer will gain access but also other applications.
A better and preferred solution is to provide the Media Player stream instead of the file path. As a result we omit attempt to access to our file from another application(MediaPlayer) and also enable audio to be played.
//some code ... FileInputStream inputStream = getContext().openFileInput(mediaId); mediaPlayer.setDataSource(inputStream.getFD()); inputStream.close();
Please note that we call
close()
method after setting data source.
Brak komentarzy :
Prześlij komentarz