加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 将pcm加载到AVAudioPCMBuffer中

发布时间:2020-12-14 04:31:32 所属栏目:百科 来源:网络整理
导读:我有这个代码: func loadSoundfont(_ pitch : String) { let path: String = Bundle.main.path(forResource: "(self.id)/(pitch)",ofType: "f32")! let url = URL(fileURLWithPath: path) do { let file = try AVAudioFile(forReading: url,commonFormat:
我有这个代码:

func loadSoundfont(_ pitch : String) {
    let path: String = Bundle.main.path(forResource: "(self.id)/(pitch)",ofType: "f32")!
    let url = URL(fileURLWithPath: path)

    do {
        let file = try AVAudioFile(forReading: url,commonFormat: AVAudioCommonFormat.pcmFormatFloat32,interleaved: true)
        let format = file.processingFormat
        let capacity = AVAudioFrameCount(file.length)
        self.buffer = AVAudioPCMBuffer(pcmFormat: format,frameCapacity: capacity)
        try file.read(into: self.buffer!)
    } catch let error as NSError {
        print("ERROR HERE",error.localizedDescription)
    }
}

我得到以下错误:1954115647这是:kAudioFileUnsupportedFileTypeError

我的A4.f32文件包含一个PCM浮动32.这里有什么我想念的吗?我的文件中没有标题,是否可能导致此问题?

解决方法

感谢Rhythmic Fistman的评论,我自己去加载它,就这样:

func loadSoundfont(_ pitch : String) {
    let path: String = Bundle.main.path(forResource: "(self.id)/(pitch)",ofType: "f32")!
    let url = URL(fileURLWithPath: path)

    do {
        let data = try Data(contentsOf: url)
        let format = AVAudioFormat(commonFormat: .pcmFormatFloat32,sampleRate: 44100,channels: 2,interleaved: true)

        self.buffer = AVAudioPCMBuffer(pcmFormat: format,frameCapacity: AVAudioFrameCount(data.count))

        self.buffer!.floatChannelData!.pointee.withMemoryRebound(to: UInt8.self,capacity: data.count) {
            let stream = OutputStream(toBuffer: $0,capacity: data.count)
            stream.open()
            _ = data.withUnsafeBytes {
                stream.write($0,maxLength: data.count)
            }
            stream.close()
        }

    } catch let error as NSError {
        print("ERROR HERE",error.localizedDescription)
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读