//
//  testRecording.swift
//  Funny_sounds
//
//  Created by 忆海16 on 2024/8/27.
//

import UIKit
import AVFoundation
class testRecording: RootVC {
    
    var audioRecorder: AVAudioRecorder?
       var audioPlayer: AVAudioPlayer?
       var recordingSession: AVAudioSession!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 初始化录音会话
        recordingSession = AVAudioSession.sharedInstance()

        do {
            try recordingSession.setCategory(.playAndRecord, mode: .default)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission { [unowned self] allowed in
                DispatchQueue.main.async {
                    if allowed {
                        // 用户允许访问麦克风
                    } else {
                        // 用户拒绝访问麦克风
                        print("用户未授权使用麦克风")
                    }
                }
            }
        } catch {
            print("录音会话配置出错: \(error.localizedDescription)")
        }

    }

    @IBAction func sta(_ sender: Any) {
        startRecording()
    }
    
    
    @IBAction func stop(_ sender: Any) {
        finishRecording(success: true)
    }
    
    
    @IBAction func play(_ sender: Any) {
        playRecording()
    }
    
    
    // 开始录音
       func startRecording() {
           let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
           let settings = [
               AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
               AVSampleRateKey: 12000,
               AVNumberOfChannelsKey: 1,
               AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
           ]

           do {
               audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
               audioRecorder?.delegate = self
               audioRecorder?.record()
               print("开始录音")
           } catch {
               finishRecording(success: false)
           }
       }
    // 停止录音
       func finishRecording(success: Bool) {
           audioRecorder?.stop()
           audioRecorder = nil

           if success {
               print("录音成功结束")
           } else {
               print("录音失败")
           }
       }
    // 播放录音
       func playRecording() {
           let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
           
           do {
               audioPlayer = try AVAudioPlayer(contentsOf: audioFilename)
               audioPlayer?.play()
               print("开始播放录音")
           } catch {
               print("播放录音出错: \(error.localizedDescription)")
           }
       }
    // 获取文档目录路径
    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

}
extension testRecording: AVAudioRecorderDelegate {
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if !flag {
            finishRecording(success: false)
        }
    }
}
