首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我将installTap缓冲区写入AVAudioFile似乎在数据方面失败了。

我将installTap缓冲区写入AVAudioFile似乎在数据方面失败了。
EN

Stack Overflow用户
提问于 2022-01-07 05:04:22
回答 1查看 147关注 0票数 0

我正在尝试将缓冲区从我的installTap保存到一个文件中。我把它分成10块,这样我就能得到一个更大的文件。当我尝试播放写好的文件(来自模拟器的目录)时,QuickTime说它不兼容。

我检查了坏的m4a文件和一个工作文件。在开始时,坏文件中有很多0的值,然后是大量的数据。但是,这两个文件的标题似乎是相同的。

很多人提到我必须放弃AudioFile,但是:

audioFile =零

不是一个有效的语法,也不能在AudioFile中提交一个close方法。

下面是完整的代码,编辑成一个工作文件:

代码语言:javascript
运行
复制
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)
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-07 08:01:00

您需要让您的AVAudioFile超出作用域(在某个时候是nil),这就是如何调用AVAudioFileclose()方法,该方法大概完成了头信息的编写。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70616820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档