Lesson 23 – Audio playback (file in raw folder) in Kotlin

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

We will see the steps to play an mp3 file (other formats supported by Android are: Ogg, Wav)

Issue:

First, create a new project called Project025.

Have two buttons with the labels: Jack and Lion, then when you press play the respective audio file. Sound files store them in the same application.

After creating the project we proceed to create a folder called raw that depends on the folder res, we store the two mp3 files in that folder (to create the folder we press the right mouse button on the folder res and select New -> Directory):

 

Lesson 23 - Audio playback (file in raw folder) in Kotlin - Lesson 23 - Audio playback (file in raw folder) in Kotlin - Lesson 23 - Audio playback (file in raw folder) in Kotlin -

Then copy the files to the folder (in Android Studio Copy / Paste works from the file manager of the Windows operating system):

 

Lesson 23 - Audio playback (file in raw folder) in Kotlin - Lesson 23 - Audio playback (file in raw folder) in Kotlin - Lesson 23 - Audio playback (file in raw folder) in Kotlin -

We create an interface with two buttons and initialize the properties text:

 

Lesson 23 - Audio playback (file in raw folder) in Kotlin - Lesson 23 - Audio playback (file in raw folder) in Kotlin - Lesson 23 - Audio playback (file in raw folder) in Kotlin -

The source code in Kotlin is:

package com.coding180.project025


import android.media.MediaPlayer
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity: AppCompatActivity () {

    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)
// coding180.com

        val button1 = findViewById (R.id.button1) as Button
        button1.setOnClickListener {
            val mp = MediaPlayer.create (this, R.raw.song1)
            mp.start ()
        }

        val button2 = findViewById (R.id.button2) as Button
        button2.setOnClickListener {
            val mp = MediaPlayer.create (this, R.raw.song2)
            mp.start ()
        }
    }
}

When we copy the mp3 files then the reference to the two files is generated in the R class and later we can rescue them when we create an object of the MediaPlayer class:

            val mp = MediaPlayer.create (this, R.raw.song1)

Next, we call the start method:

            mp.start ()

…..

About The Author

Related posts

Leave a Reply