Skip to content

音频播放

源:Android MediaPlayer | iOS AVAudioPlayer

音频播放用于播放音效和背景音乐。本文展示基础的音频播放功能。

标准代码块

kotlin
expect class AudioPlayer {
    fun play(audioPath: String)
    fun pause()
    fun stop()
    fun release()
}
kotlin
import android.media.MediaPlayer

actual class AudioPlayer {
    private var mediaPlayer: MediaPlayer? = null
    
    actual fun play(audioPath: String) {
        mediaPlayer = MediaPlayer().apply {
            setDataSource(audioPath)
            prepare()
            start()
        }
    }
    
    actual fun pause() {
        mediaPlayer?.pause()
    }
    
    actual fun stop() {
        mediaPlayer?.stop()
    }
    
    actual fun release() {
        mediaPlayer?.release()
        mediaPlayer = null
    }
}
kotlin
import platform.AVFAudio.*
import platform.Foundation.NSURL

actual class AudioPlayer {
    private var player: AVAudioPlayer? = null
    
    actual fun play(audioPath: String) {
        val url = NSURL.fileURLWithPath(audioPath)
        player = AVAudioPlayer(url, null)
        player?.play()
    }
    
    actual fun pause() {
        player?.pause()
    }
    
    actual fun stop() {
        player?.stop()
    }
    
    actual fun release() {
        player = null
    }
}