package com.soundapp.soundgags.setting

import android.content.Context
import android.media.MediaRecorder
import java.io.File
import java.io.IOException


class MediaPlayerManager(context: Context) {
    private var mediaRecorder: MediaRecorder? = null
    private val tempFileName: String
    private val fileName: String? = null
    private var isRecording = false

    init {
        val dir = context.cacheDir
        val file = File(dir, "temp_audio.mp3")
        tempFileName = file.absolutePath
    }


    fun startRecording() {
        if (isRecording) return
        mediaRecorder = MediaRecorder()
        mediaRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
        mediaRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
        mediaRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
        mediaRecorder!!.setOutputFile(tempFileName)

        try {
            mediaRecorder!!.prepare()
            mediaRecorder!!.start()
            isRecording = true
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun stopRecording() {
        if (!isRecording || mediaRecorder == null) return

        try {
            // 只有在录制状态下才能调用stop
            mediaRecorder?.stop()
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        } catch (e: RuntimeException) {
            e.printStackTrace()
        } finally {
            releaseMediaRecorder()
            isRecording = false
        }
    }
    private fun releaseMediaRecorder() {
        try {
            mediaRecorder?.release()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            mediaRecorder = null
        }
    }
    fun getTempFileName(): String {
        return tempFileName
    }
}
