我正在尝试将缓冲区从我的installTap保存到一个文件中。我把它分成10块,这样我就能得到一个更大的文件。当我尝试播放写好的文件(来自模拟器的目录)时,QuickTime说它不兼容。
我检查了坏的m4a文件和一个工作文件。在开始时,坏文件中有很多0的值,然后是大量的数据。但是,这两个文件的标题似乎是相同的。
很多人提到我必须放弃AudioFile,但是:
audioFile =零
不是一个有效的语法,也不能在AudioFile中提交一个close方法。
下面是完整的代码,编辑成一个工作文件:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let audioEngine = AVAudioEngine()
var audioFile = AVAudioFile()
var x = 0
override func viewDidLoad() {
super.viewDidLoad()
record()
// Do any additional setup after loading the view.
}
func makeFile(format: AVAudioFormat) {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
do {
_ = try FileManager.default.contentsOfDirectory(at: paths!, includingPropertiesForKeys: nil)
} catch { print ("error")}
let destinationPath = paths!.appendingPathComponent("audioT.m4a")
print ("\(destinationPath)")
do {
audioFile = try AVAudioFile(forWriting: destinationPath,
settings: format.settings)
print ("file created")
} catch { print ("error creating file")}
}
func record(){
let node = audioEngine.inputNode
let recordingFormat = node.inputFormat(forBus: 0)
makeFile(format: recordingFormat)
node.installTap(onBus: 0, bufferSize: 8192, format: recordingFormat, block: { [self]
(buffer, _) in
do {
try audioFile.write(from: buffer);
print ("buffer filled");
x += 1;
print("wrote \(x)")
if x > 9 {
endThis()
}
} catch {return};})
audioEngine.prepare()
do {
try audioEngine.start()
} catch let error {
print ("oh catch")
}
}
func endThis(){
audioEngine.stop()
audioEngine.inputNode.removeTap(onBus: 0)
}
}
发布于 2022-01-07 08:01:00
您需要让您的AVAudioFile
超出作用域(在某个时候是nil
),这就是如何调用AVAudioFile
的close()
方法,该方法大概完成了头信息的编写。
https://stackoverflow.com/questions/70616820
复制相似问题