
In this article, we’ll learn how to add and use raw files (like mp3/mp4) in Android Studio.
Prerequisites:
First, we need to create a raw folder in the res directory. Right-click on the res and select New > Android Resource Directory.

From the Resource Type menu, select the raw option and click on the OK button.

Now, in the res directory, you will find the raw folder.

Let’s add an mp3 file. First, download this sound effect from Pixabay.
Change its name to epic_hybrid_logo_effect.mp3. You should keep in mind the following rules when naming the file:
- Use small letters and numbers.
- No special character is allowed except underscore.
- The file name should start with a letter or underscore (but not a number).
Now, copy the audio file by pressing CTRL + C. Right-click on our raw folder and select the Paste option.

You will see a pop-up dialog. Click on the OK button.

Now, our file is added to the raw folder.
How to Access Raw Files?
We can access the files in the code by calling R.raw.name_of_the_file. In our case, we can get our mp3 file by calling R.raw.epic_hybrid_logo_effect.
Let’s play the song.
Add the following method to your Activity.
private fun playSong(context: Context) {
val mediaPlayer = MediaPlayer.create(context, R.raw.epic_hybrid_logo_effect)
mediaPlayer.isLooping = true
mediaPlayer.start()
}
If you are using Jetpack Compose, you can call the method like this:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
YourProjectNameTheme(darkTheme = false) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Column(
modifier = Modifier.fillMaxSize(),
) {
val context = LocalContext.current.applicationContext
// button
Button(
onClick = {
playSong(context)
}
) {
Text(text = "Play")
}
}
}
}
}
}
private fun playSong(context: Context) {
val mediaPlayer = MediaPlayer.create(this, R.raw.epic_hybrid_logo_effect)
mediaPlayer.isLooping = true
mediaPlayer.start()
}
}
If you are using XML:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// call the method on a button click
playSong(this.applicationContext)
}
private fun playSong(context: Context) {
val mediaPlayer = MediaPlayer.create(this, R.raw.epic_hybrid_logo_effect)
mediaPlayer.isLooping = true
mediaPlayer.start()
}
}
This is how you can add and use raw files in Android Studio. I hope you have learned something new. If you have any doubts, leave a comment below.
Related Articles:
…. loooooove you man … this helped a lot …. respect !!!!!!!!
Thank you 🙂