Kotlin 26. How to play audio files in Kotlin

How to play audio files in Kotlin



1 Download and place the audio file

We can download an audio file at will, for example alarm.mp3, it needs to be placed /res/raw/under the path.

2 activity_main.xml

Here, we add a button. When we press this button, the APP will play the specified music.

<Button
    android:id="@+id/pushButton"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:text="Press"
    android:textColor="@color/white"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.344" />

3 MainActivity.kt

class MainActivity : AppCompatActivity() {
    
    

    private var mediaPlayer: MediaPlayer? = null

    @SuppressLint("ClickableViewAccessibility", "ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mediaPlayer = MediaPlayer.create(this, R.raw.alarm1)
        mediaPlayer?.setOnPreparedListener{
    
    
            println("READY TO GO")
        }

        pushButton.setOnTouchListener {
    
     _, event ->
            handleTouch(event)
            true
        }
    }

    // 按下按钮后,报警声音响起
    private fun handleTouch(event: MotionEvent)
    {
    
    
        when (event.action) {
    
    
            MotionEvent.ACTION_DOWN -> {
    
    
                println("down")
                mediaPlayer?.start()
            }
            MotionEvent.ACTION_UP -> {
    
    
                println("up")
                mediaPlayer?.pause()
                mediaPlayer?.seekTo(0)
                // 使用完MediaPlayer需要回收资源。
                // MediaPlayer是很消耗系统资源的,所以在使用完MediaPlayer,不要等待系统自动回收,最好是主动回收资源。
                if (mediaPlayer != null && mediaPlayer?.isPlaying == true) {
    
    
                    mediaPlayer?.stop()
                    mediaPlayer?.release()
                    mediaPlayer = null
                }
            }
            else -> {
    
    
                println("others")
            }
        }
    }

}

The logic here is relatively straightforward, and there are a few points that need to be explained. First of all, we need to create a new MediaPlayer for playing custom music: MediaPlayer.create(this, R.raw.alarm1), here, the music is named alarm1.mp3and stored in res/raw/the folder. mediaPlayer?.setOnPreparedListenerDoesn't do anything here, what this function does is tell us when the audio is ready to play: Register a callback to be invoked when the media source is ready for playback.. When we press the button, handleTouchthe function is fired, or more precisely, handleTouchin the MotionEvent.ACTION_DOWN. mediaPlayer?.start()That is, an instruction to play music. handleTouchThe in is fired when we release the button MotionEvent.ACTION_UP. Finally, it should be noted that MediaPlayer consumes a lot of system resources, so after using MediaPlayer, do not wait for the system to automatically recycle, it is best to actively recycle resources: mediaPlayer?.stop(), mediaPlayer?.release().

Guess you like

Origin blog.csdn.net/zyctimes/article/details/128977204