Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

75. Android Audio Recording and Playback using MediaPlayer and MediaRecorder

This chapter will provide an overview of the MediaRecorder class and explain the basics of how this class can be used to record audio or video. The use of the MediaPlayer class to play back audio will also be covered. Having covered the basics, an example application will be created to demonstrate these techniques in action. In addition to looking at audio and video handling, this chapter will also touch on the subject of saving files to the SD card.

75.1 Playing Audio

In terms of audio playback, most implementations of Android support AAC LC/LTP, HE-AACv1 (AAC+), HE-AACv2 (enhanced AAC+), AMR-NB, AMR-WB, MP3, MIDI, Ogg Vorbis, and PCM/WAVE formats.

Audio playback can be performed using either the MediaPlayer or the AudioTrack classes. AudioTrack is a more advanced option that uses streaming audio buffers and provides greater control over the audio. The MediaPlayer class, on the other hand, provides an easier programming interface for implementing audio playback and will meet the needs of most audio requirements.

The MediaPlayer class has associated with it a range of methods that can be called by an application to perform certain tasks. A subset of some of the key methods of this class is as follows:

create() – Called to create a new instance of the class, passing through the Uri of the audio to be played.

setDataSource() – Sets the source from which the audio is to play.

prepare...

75.2 Recording Audio and Video using the MediaRecorder Class

As with audio playback, recording can be performed using a number of different techniques. One option is to use the MediaRecorder class, which, as with the MediaPlayer class, provides a number of methods that are used to record audio:

setAudioSource() – Specifies the source of the audio to be recorded (typically this will be MediaRecorder.AudioSource.MIC for the device microphone).

setVideoSource() – Specifies the source of the video to be recorded (for example MediaRecorder.VideoSource.CAMERA).

setOutputFormat() – Specifies the format into which the recorded audio or video is to be stored (for example MediaRecorder.OutputFormat.AAC_ADTS).

setAudioEncoder() – Specifies the audio encoder to be used for the recorded audio (for example MediaRecorder.AudioEncoder.AAC).

setOutputFile() – Configures the path to the file into which the recorded...

75.3 About the Example Project

The remainder of this chapter will work through the creation of an example application intended to demonstrate the use of the MediaPlayer and MediaRecorder classes to implement the recording and playback of audio on an Android device.

When developing applications that make use of specific hardware features, the microphone being a case in point, it is important to check the availability of the feature before attempting to access it in the application code. The application created in this chapter will, therefore, also include code to detect the presence of a microphone on the device.

Once completed, this application will provide a very simple interface intended to allow the user to record and playback audio. The recorded audio will need to be stored within an audio file on the device. That being the case, this tutorial will also briefly explore the mechanism for using SD Card storage.

75.4 Creating the AudioApp Project

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter AudioApp into the Name field and specify com.ebookfrenzy.audioapp as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

Designing the User Interface

Once the new project has been created, select the activity_main.xml file from the Project tool window and with the Layout Editor tool in Design mode, select the “Hello World!” TextView and delete it from the layout.

Drag and drop three Button views onto the layout. The positioning of the buttons is not of paramount importance to this example, though Figure 75-1 shows a suggested layout using a vertical chain.

Configure the buttons to display string resources that read Play, Record...

75.5 Checking for Microphone Availability

Attempting to record audio on a device without a microphone will cause the Android system to throw an exception. It is vital, therefore, that the code check for the presence of a microphone before making such an attempt. There are a number of ways of doing this, including checking for the physical presence of the device. An easier approach, and one that is more likely to work on different Android devices, is to ask the Android system if it has a package installed for a particular feature. This involves creating an instance of the Android PackageManager class and then making a call to the object’s hasSystemFeature() method. PackageManager.FEATURE_MICROPHONE is the feature of interest in this case.

For the purposes of this example, we will create a method named hasMicrophone() that may be called upon to check for the presence of a microphone. Within the Project tool window, locate and double-click on the MainActivity.java file and modify...

75.6 Performing the Activity Initialization

The next step is to modify the activity to perform a number of initialization tasks. Remaining within the MainActivity.java file, modify the code as follows:

package com.ebookfrenzy.audioapp;

 

import java.io.IOException;

.

.

import android.media.MediaRecorder;

import android.os.Environment;

import android.widget.Button;

import android.view.View;

import android.media.MediaPlayer; 

 

public class MainActivity extends AppCompatActivity {

 

    private static MediaRecorder mediaRecorder;

    private static MediaPlayer mediaPlayer;

 

    private static String audioFilePath;

    private Button stopButton;

    private Button playButton;

    private Button recordButton;

       

    private...

75.7 Implementing the recordAudio() Method

When the user touches the Record button, the recordAudio() method will be called. This method will need to enable and disable the appropriate buttons and configure the MediaRecorder instance with information about the source of the audio, the output format and encoding, and the location of the file into which the audio is to be stored. Finally, the prepare() and start() methods of the MediaRecorder object will need to be called. Combined, these requirements result in the following method implementation in the MainActivity.java file:

public void recordAudio (View view)

{

   isRecording = true;

   stopButton.setEnabled(true);

   playButton.setEnabled(false);

   recordButton.setEnabled(false);

          

   try {

     mediaRecorder = new MediaRecorder();

  ...

75.8 Implementing the stopAudio() Method

The stopAudio() method is responsible for enabling the Play button, disabling the Stop button and then stopping and resetting the MediaRecorder instance. The code to achieve this reads as outlined in the following listing and should be added to the MainActivity.java file:

public void stopAudio (View view)

{

              

       stopButton.setEnabled(false);

       playButton.setEnabled(true);

              

       if (isRecording)

       {

              recordButton.setEnabled(false);

             ...

75.9 Implementing the playAudio() method

The playAudio() method will simply create a new MediaPlayer instance, assign the audio file located on the SD card as the data source and then prepare and start the playback:

public void playAudio (View view) throws IOException

{

       playButton.setEnabled(false);

       recordButton.setEnabled(false);

       stopButton.setEnabled(true);

 

       mediaPlayer = new MediaPlayer();

       mediaPlayer.setDataSource(audioFilePath);

       mediaPlayer.prepare();

       mediaPlayer.start();

}

75.10 Configuring and Requesting Permissions

Before testing the application, it is essential that the appropriate permissions be requested within the manifest file for the application. Specifically, the application will require permission to record audio and to access the external storage (SD card). Within the Project tool window, locate and double-click on the AndroidManifest.xml file to load it into the editor and modify the XML to add the two permission tags:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.ebookfrenzy.audioapp" >

 

    <uses-permission android:name=

                 "android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="...

75.11 Testing the Application

Compile and run the application on an Android device containing a microphone, allow the requested permissions and touch the Record button. After recording, touch Stop followed by Play, at which point the recorded audio should play back through the device speakers. If running on Android 6.0 or later, note that the app requests permission to use the external storage and to record audio when first launched.

75.12 Summary

The Android SDK provides a number of mechanisms for the implementation of audio recording and playback. This chapter has looked at two of these, in the form of the MediaPlayer and MediaRecorder classes. Having covered the theory of using these techniques, this chapter worked through the creation of an example application designed to record and then play back audio. In the course of working with audio in Android, this chapter also looked at the steps involved in ensuring that the device on which the application is running has a microphone before attempting to record audio. The use of external storage in the form of an SD card was also covered.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth