In our application, it's sometimes necessary to play an audio file.
The android sdk offers us a simple way to do it.
let's examine the small snippet of code which does it:
MediaPlayer mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.audiofile);
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mPlayer.start();
explanation:
MediaPlayer - MediaPlayer class can be used to control playback of audio/video files and
streams. we need to pass : context and an id of the audio file, we will save the file under
the "raw" folder under the familiar "res" folder.
after which we must call mPlayer.prepare() - Prepares the player for playback, synchronously.
After setting the datasource and the display surface, you need to either call prepare() or prepareAsync(). For files, it is OK to call prepare(), which blocks until MediaPlayer is ready for playback.