- Examining the ImageView Control
- Bitmaps and Canvas
- Using VideoViews
- Playing Audio with MediaPlayer
- Exploring More Media Options
- Summary
- Q&A
- Workshop
- Exercise
Playing Audio with MediaPlayer
Now consider a simple example of playing an .MP3 audio file using a MediaPlayer(android.media.MediaPlayer). When you do this, you are responsible for the state of the MediaPlayer. A MediaPlayer can be reset() and must be released when you are done using it.
The code for this example is in the Hour21Audio project in MainActivity.java. In the example, you read a file called helloworld.mp3 from the assets directory. You do this in the onResume() method. The MediaPlayer is released in the onPause() method.
Listing 21.9 shows the onResume() method of MainActivity.java. The audio file is read from the assets folder and played using a MediaPlayer.
Listing 21.9 Playing an MP3 Audio File
1: protected void onResume() { 2: super.onResume(); 3: try { 4: audioFileDescriptor = getAssets().openFd("helloworld.mp3"); 5: mediaPlayer.setDataSource(audioFileDescriptor.getFileDescriptor(), 6: audioFileDescriptor.getStartOffset(),audioFileDescriptor.getLength()); 7: mediaPlayer.prepare(); 8: mediaPlayer.start(); 9: } catch (IOException e) { 10: e.printStackTrace(); 11: } 12: }