prank/Funny_sounds/Recording/C/testRecording.swift
2024-09-03 09:38:34 +08:00

112 lines
3.1 KiB
Swift

//
// 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)
}
}
}