在单独的类中录制和播放语音(Swift3)

时间:2017-05-27 04:53:23

标签: swift avaudioplayer avaudiorecorder

我使用了许多用于录制的代码播放语音,但大多数代码都不在swift3中,而且它们在我的应用中无效。

This代码有效,但我想从viewcontroller创建一个单独的类来记录播放的声音。另外提到的github代码很复杂,我正在寻找一个简化的代码。

更新:

录制后,当我检查录制文件是否存在时,该文件不存在,并在appDelegate上引发EXC_BAD_ACCESS错误。

怎么了?

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:4)

尝试通过线路录制音频

let isRec = AudioManager.shared.record(fileName: "rec")

如果isRec返回true,则记录不会发生。 要完成录制,请使用:let recordedURL = AudioManager.shared.finishRecording()

播放录制的文件,将以上网址发送到经理类

中的setupUpPlayer()功能

不要忘记使用扩展程序代码段,在代码段下方提供AVAudioRecorderAVAudioPlayer

的委托功能
import Foundation

import AVFoundation

class AudioManager: NSObject {

static let shared = AudioManager()

var recordingSession: AVAudioSession?
var recorder: AVAudioRecorder?
var meterTimer: Timer?
var recorderApc0: Float = 0
var recorderPeak0: Float = 0
//PLayer
var player: AVAudioPlayer?
var savedFileURL: URL?

func setup() {
    recordingSession = AVAudioSession.sharedInstance()
    do {
        try recordingSession?.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
        try recordingSession?.setActive(true)
        recordingSession?.requestRecordPermission({ (allowed) in
            if allowed {
                print("Mic Authorised")
            } else {
                print("Mic not Authorised")
            }
        })
    } catch {
        print("Failed to set Category", error.localizedDescription)
    }
}

func record(fileName: String) -> Bool {
    setup()
    let url = getUserPath().appendingPathComponent(fileName + ".m4a")
    let audioURL = URL.init(fileURLWithPath: url.path)
    let recordSettings: [String: Any] = [AVFormatIDKey: kAudioFormatMPEG4AAC,
                                         AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
                                         AVNumberOfChannelsKey: 2,
                                         AVSampleRateKey: 44100.0]
    do {
        recorder = try AVAudioRecorder.init(url: audioURL, settings: recordSettings)
        recorder?.delegate = self
        recorder?.isMeteringEnabled = true
        recorder?.prepareToRecord()
        recorder?.record()
        self.meterTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (timer: Timer) in
            //Update Recording Meter Values so we can track voice loudness
            if let recorder = self.recorder {
                recorder.updateMeters()
                self.recorderApc0 = recorder.averagePower(forChannel: 0)
                self.recorderPeak0 = recorder.peakPower(forChannel: 0)
            }
        })
        savedFileURL = url
        print("Recording")
        return true
    } catch {
        print("Error Handling", error.localizedDescription)
        return false
    }
}

func getUserPath() -> URL {
    return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}

func finishRecording() -> String {
    recorder?.stop()
    self.meterTimer?.invalidate()
    var fileURL: String?
    if let url: URL = recorder?.url {
        fileURL = String(describing: url)
    }
    return /fileURL
}
//Player
func setupPlayer(_ url: URL) {
    do {
        try player = AVAudioPlayer.init(contentsOf: url)
    } catch {
        print("Error1", error.localizedDescription)
    }
    player?.prepareToPlay()
    player?.play()
    player?.volume = 1.0
    player?.delegate = self
}
}
    //MARK:- Audio Recorder Delegate

    extension AudioManager: AVAudioRecorderDelegate {

    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {

        print("AudioManager Finish Recording")

    }
    func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
        print("Encoding Error", /error?.localizedDescription)
    }

}
    //MARK:- Audio Player Delegates

    extension AudioManager: AVAudioPlayerDelegate {

       func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, 
   successfully flag: Bool) {

           player.stop()

           print("Finish Playing")

       }

       func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, 
    error: Error?) {

            print(/error?.localizedDescription)

        }

    }