Android Studio Audio Player [Part 2] Playing, pausing, resume, stopping an audio

You can refer to all source codes here: https://github.com/leonardltk/AndroidAudioWaveViewer
The end product should look like this.

This is is part 2 of the series.

  1. Setting up the interface.
  2. Playing, pausing, resume, stopping an audio.
  3. Loading the audio into data array.
  4. Plotting the data into a waveplot canvas for visualisation.
  5. Enable scrolling of the canvas.
  6. Having a slider to show the current wave time.

Playing, pausing, resume, stopping an audio

From the Palette, draw a Button down to the layout, and drag the blue circular buttons to the top, down, left, right of the page.

On the code section, we see that it is constrained to the “parent”, which is the white canvas.

If we don’t do this, on the app, it will jump to the top left of the app because it does not know where to place this button. This ensure a relative placement.

Now, we set an identifier for this button, call it “PlayButton”, there will be a pop up, make sure to Refactor it, so it affects the rest of the script when u choose to rename it.

On the Attributes tab on the right, change the text to “Play”. This button will serve to play music.

On the code section, notice that it asks us to Extract String Resource. This means this button will draw the test from “res/values/strings.xml”. This is not compulsory, but is recommended as a good practice. In the code section, we now have android:text=“@string/play” instead of the previous android:text=“Play”

When we have many buttons in the future, storing the text of the buttons in strings.xml makes it neater.
set PlayAudio for onClick.

Now, under the code section, type in android:onClick=“PlayAudio”, or alternatively, if you prefer, write it in under the Attributes section on the right. What this means is that when you press the button on the app, it will run the PlayAudio function that you defined in the main script. Now lets define it.

Under the MainActivity.java, define these.

We go though each section one by one.

/** ------------ Init ------------ */
// Template song
public MediaPlayer mySong;

This initializes the variable mySong as a MediaPlayer. This will be used to read the audio file, and to play it.

/** ------------ When App start, run these by default ----------- */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySong = MediaPlayer.create(this, R.raw.test);
}

This default function OnCreate is what happens when you start up the app. It will run these immediately. First, setContentView will display the activity_main, which we have modified just now, by adding a play button. Then, MediaPlayer.create calls the test.wav from the res/raw folder, which is identified as R.raw.test, and set it to mySong variable.

/** ------------ Play Pause/Resume Stop Buttons. ------------ */
public void PlayAudio(View view){
/** Play Song */
mySong.start();
}

Now, this is where we defined the PlayAudio function, which the Play button will call upon clicking, because we set it to android:onClick=“PlayAudio” in the activity_main.xml. mySong.start plays the song, which was created in onCreate.

Now, when you run the app, there will be a button Play, and when u click on it, it will play the song in your res/raw folder, which you named test.wav.

It will play all the way to the end. Now we add on additional functions such as pause, resume, and stopping.

Adding Stop functionality

Disabling the right constraint, to allow merging with a new button.

On the Play button, hold Ctrl, and click the right blue circular button. Alternatively, at the code section, delete the line app:layout_constraintEnd_toEndOf=”parent” . This cancels the constraint to the right end of the layout.

Following the same procedure as above, we create the Stop button. Then, from the right circular button of the Play button, which we previously cancelled the constraint to the layout, we now constrain it to the left of the Stop button. Then for the rest of the Stop constraints, constrain them to the parent.

On the layout of the Stop button, we click on the Create Left Constraint which is the blue circle with the + sign. This links it back to whichever is constrained to it, which is the Play Button at the moment.

Set the number in red (highlighted in red) from 117 to 0, as it means a fixed offset from the left. Use the horizontal bias slider (highlighted in blue) instead, if you want to shift it closer or further from the adjacent buttons. for now we keep it center. Similarly, we add the stop functionality android:onClick=”StopAudio” and define it in the main script.

<Button
android:id=”@+id/StopButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginStart=”117dp”
android:onClick=”PauseResumeAudio”
android:text=”@string/stop”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintStart_toEndOf=”@+id/PlayButton”
app:layout_constraintTop_toTopOf=”parent” />

First we set mySong.release to stop playing the current song.

Then we reinitialize it by calling MediaPlayer.create, which was previously done in the onCreate.

public void StopAudio(View view){
/** Stop Song */
mySong.release();
mySong = MediaPlayer.create(this, R.raw.test);
}

Adding Pause functionality

In the same way as above, we insert a new button called the Pause button, have them horizontally inline with the Play and Stop button, and link it to function PauseResumeAudio.

Now it should look like this.

Now, defining the PauseResumeAudio is a little bit more involved, as compared to PlayAudio or StopAudio.

Our goal for this button is to pause the current song, and change its text to Resume, and then when we click on it again, we resume where we left off, and change the button text back to Pause.

TextView is meant for us to edit the text of buttons. So we initialize it to PauseResumeTextView.

PauseResumeFlag is an indicator to show whether the current button is meant to pause or resume the playback.

PausedLength is meant for determining the length of the audio that has played, and we resume from it again later.

// Button Params
TextView PauseResumeTextView;
public int PauseResumeFlag=0, PausedLength;

Now under PauseResumeAudio, we have two things we to do, either to pause it, or to resume play back. Assuming the audio is currently playing.

/** Pause */
if (PauseResumeFlag == 0){
/** Pause song */
mySong.pause();
PausedLength = mySong.getCurrentPosition();

/** Set flag and Button Text to Resume */
PauseResumeFlag = 1;
PauseResumeTextView.setText("Resume");
}

First, we define PauseResumeFlag=0 as indication to pause the audio. We pause by using mySong.pause. Since it has paused, setting PausedLength to mySong.getCurrentPosition allows us to know where to continue from later when we want to resume.

Then we set PauseResumeFlag=1, so that later when we press the resume button, we don’t enter this condition. And now we edit the button text to show Resume by using PauseResumeTextView.setText.

/** Resume */
else {
/** Resume song */
mySong.seekTo(PausedLength);
mySong.start();

/** Set flag and Button Text to Pause */
PauseResumeFlag = 0;
PauseResumeTextView.setText("Pause");
}

When the audio is paused, PauseResumeFlag=1 now. From the previously saved PausedLength, we can continue where we left off by using mySong.seekTo, then start playing from there using mySong.start.

Similar to the Pause action, Then we set PauseResumeFlag=0, and edit the button text to show Pause.

Now we have it, the playing, pausing, resuming, and stopping of audio from the buttons. Next, we will learn how to load the audio into data array.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store