package com.example.chemical.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.net.Uri

@Deprecated(
    "没有释放资源,并且占用context,容易内存泄露",
    ReplaceWith("AudioPlayer"),
    DeprecationLevel.WARNING
)
object MediaPlayerHelper {
    private var mediaPlayer: MediaPlayer? = null

    fun playRawMp3(context: Context, resId: Int) {
        stopAudio()

        val uri = Uri.parse("android.resource://${context.packageName}/$resId")

        mediaPlayer = MediaPlayer().apply {
            setAudioAttributes(
                AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .build()
            )

            setDataSource(context, uri)
            prepareAsync()

            setOnPreparedListener {
                start()
            }

            setOnCompletionListener {
                stopAudio()
            }
        }
    }

    private fun stopAudio() {
        mediaPlayer?.apply {
            stop()
            release()
        }
        mediaPlayer = null
    }
}