load a pcm into a AVAudioPCMBuffer

前端 未结 1 1586
遥遥无期
遥遥无期 2021-02-10 07:59

I have this code:

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


        
1条回答
  •  遇见更好的自我
    2021-02-10 08:23

    Thanks to Rhythmic Fistman in the comments, I went and loaded it myself, that way:

    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)
        }
    }
    

    0 讨论(0)
提交回复
热议问题