将pcm加载到AVAudioPCMBuffer中

时间:2016-12-13 23:36:02

标签: swift swift3 avfoundation

我有这段代码:

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.这里有什么我想念的吗?我的文件中没有标题,是否可能导致此问题?

1 个答案:

答案 0 :(得分:1)

感谢评论中的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)
    }
}