![]() |
VOOZH | about |
In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a Media Player, playing, pausing, starting, and stopping the media. In this article, we will show you how you could play an Audio File on Android using Jetpack Compose. Follow the below steps once the IDE is ready.
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Navigate to app > res, now right click on the res folder and select New > Android resource directory, specify name and type as raw and select Ok. Now, right click on the raw folder and paste your music file. In this project, the audio file name is "sample.mp3" and so the resource names to call it inside the application becomes R.raw.sample.
To create a raw folder, follow this article Resource Raw Folder in Android Studio.
Import two vector assets of your choice for displaying the start and pause button. In this project, we will be using the play and pause button icon available by default in the android library. To access those, we will use the attribute, android.R.drawable.ic_media_play and android.R.drawable.ic_media_pause.
To import vector assets in your Android project, follow this article How to Add Vector Assets in Android Studio?
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity.kt: