5

I have this code:

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

And I get the following error: 1954115647 which is: kAudioFileUnsupportedFileTypeError

My A4.f32 file contains a PCM float 32. Is there something I'm missing here? There's no header in my file, is it something that could lead to this problem?

Julien Fouilhé
  • 2,583
  • 3
  • 30
  • 56
  • 1
    Your audio file is raw float32 data? I don't think `AVFoundation` will load that for you. Either load it yourself or put a header on it. – Rhythmic Fistman Dec 13 '16 at 23:49
  • @RhythmicFistman Perhaps you can help me here: https://stackoverflow.com/questions/55306996/playing-wav-data-with-avaudioengine – aleclarson Mar 22 '19 at 20:37

1 Answers1

1

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)
    }
}
Julien Fouilhé
  • 2,583
  • 3
  • 30
  • 56