繁体   English   中英

使用AVAudioRecorder录制语音

[英]Using AVAudioRecorder to record voice

我正在尝试制作一个简单的录音机。 我正在使用Xcode-beta 7,而且我的代码基于这三个来源。

我正在使用以下代码:

var recordSettings = [
        AVFormatIDKey: kAudioFormatAppleIMA4,
        AVLinearPCMIsBigEndianKey: 0,
        AVLinearPCMIsFloatKey: 0,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey: 32000
    ]

    var session = AVAudioSession.sharedInstance()

    do{
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        recorder = AVAudioRecorder(URL: filePath, settings: recordSettings, error: nil)
    }catch{
        print("Error")
    }

但它说“找不到类型为'AVAudioRecorder'的初始值设定项接受类型'的参数列表'(URL:NSURL?,设置:[String:AudioFormatID],错误:nil)'”

我的输入不是文档所要求的吗?

AVAudioRecorder不再需要error参数:

init(URL url: NSURL, settings settings: [String : AnyObject]) throws

此外,我需要解开filePath,如上一个答案所示:

func recordSound(){
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

    let recordingName = "my_audio.wav"
    let pathArray = [dirPath, recordingName]
    let filePath = NSURL.fileURLWithPathComponents(pathArray)
    let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
            AVEncoderBitRateKey: 16,
            AVNumberOfChannelsKey: 2,
            AVSampleRateKey: 44100.0]
    print(filePath)

    let session = AVAudioSession.sharedInstance()
    do {
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        audioRecorder = try AVAudioRecorder(URL: filePath!, settings: recordSettings as! [String : AnyObject])
    } catch _ {
        print("Error")
    }

    audioRecorder.delegate = self
    audioRecorder.meteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()
}

您的filePath被包装为optionnal。 你应该检查是否不是n并打开它像这样:

recorder = AVAudioRecorder(URL: filePath!, settings: recordSettings, error: nil)

你还需要传递一个NSError指针:

var error: NSError?
recorder = AVAudioRecorder(URL: filePath!, settings: recordSettings, error: &error)

之后,如果你的设置dictionnay中有错误,请尝试将所有Tnt转换为NSNumber,因为NSNumber是一个Object,而不是Int。 例:

NSNumber(integer: kAudioFormatAppleIMA4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM