swift 录音服务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 录音服务相关的知识,希望对你有一定的参考价值。

import Foundation
import AVFoundation

class AudioRecordingService: NSObject {
    
    private let recordingSession = AVAudioSession.sharedInstance()
    private(set) var audioRecorder: AVAudioRecorder!
    private(set) var audioPlayer: AVAudioPlayer?
    
    //MARK: - Public methods
    
    public func startRecordingProcess() {
        print("Audio recording has started.")
        
        do {
            try recordingSession.setCategory(.playAndRecord, mode: .default)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission { [unowned self] allowed in
                DispatchQueue.main.async {
                    if allowed {
                        self.record()
                    } else {
                        print("Recording is restricted by user.")
                    }
                }
            }
        } catch {
            print("Error while requesting permissions: \(error.localizedDescription).")
        }
    }
    
    public func stopRecording() {
        audioRecorder.stop()
        audioRecorder = nil
        print("Audio record finished.")
    }
    
    public func playRecord() {
        let url = getDocumentsDirectory().appendingPathComponent("voiceRecord.aac")
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.play()
        } catch {
            print("Error: can't play audio. \(error.localizedDescription).")
        }
    }
    
    //MARK: - Private methods
    
    private func record() {
        let audioFilePath = getDocumentsDirectory().appendingPathComponent("voiceRecord.aac")
        print("File saved at: \(audioFilePath.absoluteString)")
        
        let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                         AVSampleRateKey: 12000,
                         AVNumberOfChannelsKey: 1,
                         AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ]
        
        do {
            audioRecorder = try AVAudioRecorder(url: audioFilePath, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.record()
        } catch {
            print("Error! \(error.localizedDescription)")
        }
    }
    
    private func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    
}

extension AudioRecordingService: AVAudioRecorderDelegate {
    //TODO: research
//    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
//        stopRecording()
//    }
}

以上是关于swift 录音服务的主要内容,如果未能解决你的问题,请参考以下文章

Swift + AVAudioRecorder 非常安静地录制

Swift 中的实时录音

Swift - 制作一个录音机(声音的录制与播放)

使用 Swift 将录音上传到 Firebase

swift上的iOS录音机可视化

Swift实现iOS录音与播放音频功能