2016-12-13 86 views
3

我有这样的代码:负荷PCM成AVAudioPCMBuffer

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有我在这里错过了什么?我的文件中没有标题,是否会导致此问题?

+0

您的音频文件是原始数据FLOAT32?我不认为'AVFoundation'会为你加载。要么自己加载它,要么在上面加上一个标题。 –

回答

1

由于艺术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) 
    } 
}