使用AVAudioRecorder录制文件,录制后无法获取文件路径

时间:2017-04-30 20:12:51

标签: avfoundation avaudiosession avaudiorecorder

以下是我用来制作音频文件的代码,这里的一切似乎都运行良好:

func startRecording() {
    let audioFilename = getDocumentsDirectory().appendingPathComponent("Meeting_Audio.m4a")

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

    do {
        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()

    } catch {
        finishRecording(success: false)
    }
}

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


@IBAction func onEndMeetingButtonClicked(_ sender: UIButton) {
    finishRecording(success: true)
}

func finishRecording(success: Bool) {
    audioRecorder.stop()
    audioRecorder = nil

    if success {
        print("recording succeeded :)")
    } else {
        print("recording failed :(")
    }
}

这是我的功能的简化版本,仍然可以重现问题。我从audioRecorderDidFinishRecording调用此函数。我似乎无法获得文件路径。

func makeFileData() {

    if let filePath = Bundle.main.path(forResource: "Meeting_Audio", ofType: "m4a"){
        print("File path loaded.")

        if let fileData = NSData(contentsOfFile: filePath) {
            print("File data loaded.")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您正在将文件写入一个地方:

// Documents directory!
let audioFilename = getDocumentsDirectory().appendingPathComponent("Meeting_Audio.m4a")

从另一个人那里阅读:

// app bundle!
let filePath = Bundle.main.path(forResource: "Meeting_Audio", ofType: "m4a")

尝试从您写入的位置读取文件,如下所示:

if let fileUrl = Bundle.main.url(forResource: "Meeting_Audio", withExtension: "m4a"){
    print("File path loaded.")

    if let fileData = NSData(contentsOf: fileUrl) {
        print("File data loaded.")
    }
}