How to play sound in Android?
Purpose
In this post, I will demonstrate how to play sound or audio in an Android application.
Solution
First step: Convert an audio file into an Android-compatible format
For Mac users, you can open the audio file in QuickTime Player and export it to a 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.
Second step: Add the audio file to Android Studio
Place your audio file in the src/main/res/raw
directory:
src/main/res/raw/tititi.m4a
Third step: Create playback UI and logic
Add a button to your layout file:
<Button android:id="@+id/cbTestNotif2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Play Sound" android:onClick="onTestPlaySound" android:layout_centerVertical="true" android:layout_centerHorizontal="true" />
Implement the click handler in your activity:
public void onTestPlaySound(View view) { new Thread(new Runnable() { @Override public void run() { MediaPlayer player = MediaPlayer.create( AboutActivity.this, R.raw.tititi); player.start(); } }).start();}
Key implementation details:
MediaPlayer player = MediaPlayer.create( AboutActivity.this, R.raw.tititi);player.start();
Summary
To implement audio playback in Android:
- Convert audio files to Android-supported formats like m4a
- Store files in the
res/raw
directory for resource access - Use MediaPlayer with proper threading
- Trigger playback through UI components
The complete solution combines proper resource management with Android’s MediaPlayer API while maintaining responsive UI through background threading.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!