2016-12-13 85 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) 
    } 
}