others-how to play sound in android?

1. Purpose

In this post, I will demonstrate how to play sound or audio in android app.



2. Solution

2.1 First step: convert an audio file into an android raw audio file

For mac users, you can just open the audio file in quicktime player, then export it in quicktime player to a new format like ‘m4a’.

What is m4a?

MPEG-4 audio files with M4A file extension usually contain digital audio stream encoded with AAC or ALAC (Apple Lossless Audio Codec) compression standards

2.2 Second step: put the audio file into android studio

Then , we can put the audio file into src/main/res/raw directory:

src/main/res/raw/tititi.m4a

2.3 Third step: Create UI to play audio

Now we can create a button in the layout:

        <Button
            android:id="@+id/cbTestNotif2"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="onTestPlaySound"
            android:onClick="onTestPlaySound"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />

then create the event when user click the button, here we play the sound using MediaPlayer:

    public void onTestPlaySound(View view) throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaPlayer player = MediaPlayer.create(
                        AboutActivity.this, R.raw.tititi);
                player.start();
            }
        }).start();

    }

The most important part is:

MediaPlayer player = MediaPlayer.create(
                        AboutActivity.this, R.raw.tititi);
player.start();

Now it works!



3. Summary

In this post, I demonstrated how to play sound in android app, the key point is to put the audio file in res/raw directory, and then use MediaPlayer to play it. That’s it, thanks for your reading.