Tip: Play sound from internal storage

Why play sound from internal storage?
Ordinary we play sounds (songs, ring tunes, ...) from mobile 's sdcard. But in some case, we have a sound file in internal storage(ex: default ring tunes of devices, downloaded file, device does not have a sdcard, ...), and we need to play it without copying to sdcard.

And the code:

FileInputStream fileInputStream = new FileInputStream(path);
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(fileInputStream.getFD());
mp.prepare();
Note:
- Close fileInputStream when mediaPlayer completed.
- Don't forget to add a permission READ_INTERNAL_STORAGE to Manifest:
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

P/s: Before publishing this post, I developed an application for English Learning. It has some Listening Practices. There 're some problems when streaming file from server. So i created a downloading service to download all sound files to internal storage and play them. So, this code is helpful for me.

Leave a Reply

Powered by Blogger.