小编典典

在Swift中录制音频

swift

有谁知道我在哪里可以找到有关如何在Swift应用程序中录制音频的信息?我一直在看一些音频播放示例,但是在实现音频记录方面似乎找不到任何东西。谢谢


阅读 285

收藏
2020-07-07

共1个答案

小编典典

这是代码。您可以轻松地进行记录。将此代码写在上。IBAction它将Documents按名称保存记录recordTest.caf

//declare instance variable 
var audioRecorder:AVAudioRecorder!
func record(){        
    var audioSession:AVAudioSession = AVAudioSession.sharedInstance()
    audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
    audioSession.setActive(true, error: nil)

    var documents: AnyObject = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true)[0]
    var str =  documents.stringByAppendingPathComponent("recordTest.caf")
    var url = NSURL.fileURLWithPath(str as String)

    var recordSettings = [AVFormatIDKey:kAudioFormatAppleIMA4,
        AVSampleRateKey:44100.0,
        AVNumberOfChannelsKey:2,AVEncoderBitRateKey:12800,
        AVLinearPCMBitDepthKey:16,
        AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue]

    println("url : \(url)")
    var error: NSError?

    audioRecorder = AVAudioRecorder(URL:url, settings: recordSettings, error: &error)
    if let e = error {
        println(e.localizedDescription)
    } else {
        audioRecorder.record()
    }        
}
2020-07-07