使用 AVAudioRecorder 录制文件,录制后无法获取文件路径
Posted
技术标签:
【中文标题】使用 AVAudioRecorder 录制文件,录制后无法获取文件路径【英文标题】:Recording file with AVAudioRecorder, unable to get path to file after recording 【发布时间】:2017-04-30 20:12:51 【问题描述】:这是我用来制作音频文件的代码,这里一切似乎都正常:
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】:您正在将文件写入一个位置:
// 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.")
【讨论】:
以上是关于使用 AVAudioRecorder 录制文件,录制后无法获取文件路径的主要内容,如果未能解决你的问题,请参考以下文章