在iOS 10上录制M4A文件

在iOS 10上录制M4A文件,ios,swift,Ios,Swift,我正在尝试用M4分机录音。我使用了以下代码: try! self.audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker) try! self.audioSession.setActive(true) /

我正在尝试用M4分机录音。我使用了以下代码:

            try! self.audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord,
                withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker)

            try! self.audioSession.setActive(true)


            //get documnets directory
            let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
            let fullPath = documentsDirectory.stringByAppendingPathComponent("voiceRecord.m4a")
            let url = NSURL.fileURLWithPath(fullPath)

            //create AnyObject of settings
            let settings: [String : AnyObject] = [
                AVFormatIDKey:Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey:44100.0,
                AVNumberOfChannelsKey:1,
                AVEncoderBitRateKey:12800,
                AVLinearPCMBitDepthKey:16,
                AVEncoderAudioQualityKey:AVAudioQuality.Low.rawValue
            ]

            //record
            try! self.audioRecorder = AVAudioRecorder(URL: url, settings: settings)
            self.audioRecorder.record()
            print("kayıt başladı")
此代码正在创建一个大小为28字节的.m4a文件。如果记录长度为30秒或5秒,则文件大小为28字节并不重要。正如您所想象的,该文件已损坏


问题在哪里?为什么这不能正常工作?

好的,我找到了答案。将我的设置更改为:

            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 12000,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
            ]

问题消失了。

您应该调用
prepareToRecord()
。设置代理并检查是否存在问题(
AudioRecorderEncodeErrorDidOccurse(\uRecorder:error:)
)。@Larme我实现了它,但它没有返回任何可以检查的内容:您是否在真实设备中测试?是的,我在真实设备中测试,
requestRecordPermission