在单独的班级中录制和播放语音(Swift3) [英] Record And Play Voice in Separate Class (Swift3)

查看:76
本文介绍了在单独的班级中录制和播放语音(Swift3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了许多用于录制声音播放的代码,但是其中大多数都不在swift3中,并且在我的应用中不起作用.

I used many codes that was for record an play the voice, but most of them are not in swift3 and they don't work in my app.

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

This code works, but I want to create a separate class from the viewcontroller that do recording an playing voices. Also the mentioned github code is complex an I'm searching for a simplified code.

更新:

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

After recording, when I check existence of the recorded file, the file doesn't exist, and it raises EXC_BAD_ACCESS error on appDelegate.

怎么了?

任何建议将不胜感激.

推荐答案

尝试通过布线记录音频

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

如果isRec返回true,则表示正在进行记录,否则不进行记录. 要完成录制,请使用:let recordedURL = AudioManager.shared.finishRecording()

if isRec returned true then recording is happening else not. To finish recording use : let recordedURL = AudioManager.shared.finishRecording()

要播放录制的文件,请在url上方发送到管理器类中的setupUpPlayer()函数

To play recorded file send above url to setupUpPlayer() function in manager class

不要忘记使用扩展代码段,这些代码段在AVAudioRecorderAVAudioPlayer

Not to forget to use extension code snippets give below the code snippet which are delegate functions of AVAudioRecorder and AVAudioPlayer

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)

        }

    }

这篇关于在单独的班级中录制和播放语音(Swift3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆