gpt4 book ai didi

swift - 来自 AVAudioFile 的 AVAsset 的持续时间为 0

转载 作者:可可西里 更新时间:2023-11-01 00:57:27 25 4
gpt4 key购买 nike

我正在尝试录制来自麦克风的音频 + 然后将其与来自多个位置的视频组合以创建带有来自麦克风的音频的单个视频。

使用 AVCaptureDevice + AVCaptureSession 有点断断续续,我想进行语音识别,所以我转而使用 AVCaptureSession 进行视频捕获,我正在尝试使用 AVAudioEngine 进行音频(因为我的理解是它是很容易将 SFSpeechRecognizer 附加到 AudioTap)

代码如下:

class AudioCaptureSession {

var engine = AVAudioEngine()
var outputFile : AVAudioFile!

func initAudioEngine() {
engine.stop()
engine.reset()
engine = AVAudioEngine()

do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
let ioBufferDur = 128.0/44100.0
try AVAudioSession.sharedInstance().setPreferredIOBufferDuration(ioBufferDur)
} catch {
print("AVAudioSession setup error: \(error)")
}
let outputPath = NSTemporaryDirectory().appending(kTempAudioFilename)
let outputFile = URL(fileURLWithPath: outputPath, isDirectory: false)
if FileManager.default.fileExists(atPath: outputPath) {
do {
try FileManager.default.removeItem(at: outputFile)
} catch {
print("Filemanager can't delete the audio file: \(error)")
}
}
do {
print("Settings: \(engine.mainMixerNode.outputFormat(forBus: 0).settings)")
try self.outputFile = AVAudioFile(forWriting: outputFile, settings: engine.mainMixerNode.outputFormat(forBus: 0).settings)
} catch {
print("Can't make file for writing: \(error)")
}
let input = engine.inputNode!
let format = input.inputFormat(forBus: 0)
engine.connect(input, to: engine.mainMixerNode, format: format)
engine.prepare()
try! engine.start()

}

func startRecord() {
let mixer = engine.mainMixerNode
let format = mixer.outputFormat(forBus: 0)

mixer.installTap(onBus: 0, bufferSize: 1024, format: format) { (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in
do {
try self.outputFile.write(from: buffer)
} catch {
print("Can't write audio to file: \(error)")
}
}
}

func stopRecord() {
print("Audio len: \(self.outputFile.length)")
engine.mainMixerNode.removeTap(onBus: 0)
do {
let f = try AVAudioFile(forReading: outputFile.url)
print("Length of reading file: \(f.length)")
print("Pos: \(f.framePosition)")
} catch {
print("Error getting file for reading: \(error)")
}
let asset = AVAsset(url: outputFile.url)
print("Stop recording asset duration: \(asset.duration)")

}
}

启动+停止后的示例输出是:

Audio len: 105840
Length of reading file: 0
Stop recording asset: CMTime(value: 0, timescale: 44100, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)

正如您所见,outputFile 知道它有 N 个单位长,但如果我打开一个文件进行读取,它认为它是 0,并且 AVAsset 也认为它的持续时间为 0。我想知道文件是否没有保存?或者其他的东西?我完全不知所措,因为我所看到的一切都只是说“制作一个 AVAudioFile,file.write(缓冲区),使用文件”,这显然是行不通的。我必须导出它吗?还是什么?

最佳答案

AVAudioFile 没有显式关闭,因此您需要在完成写入后通过设置 self.outputFile = nil 让它超出范围

关于swift - 来自 AVAudioFile 的 AVAsset 的持续时间为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42660090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com