2017-02-11 63 views
1

一個wav音頻文件,我現在有這樣的流程:我錄製的Audioengine音頻,將它發送到音頻處理庫,並得到一個音頻緩衝回來,然後我有堅強的意志,把它寫入一個wav文件,但我完全糊塗了怎麼辦,在迅速。花車寫入陣列中迅速

我試圖從另一個計算器回答這個片段,但它寫入一個空和損壞的文件。(load a pcm into a AVAudioPCMBuffer

//get data from library 

var len : CLong = 0 
let res: UnsafePointer<Double> = getData(CLong(), &len) 
let bufferPointer: UnsafeBufferPointer = UnsafeBufferPointer(start: res, count: len) 

//tranform it to Data 

let arrayDouble = Array(bufferPointer) 
let arrayFloats = arrayDouble.map{Float($0)} 
let data = try Data(buffer: bufferPointer) 

//attempt to write in file 
    do { 
     let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 2, interleaved: false) 

     var buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(data.count)) 
     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() 
     } 
     //settings are from AudioEngine.inputNode!.inputFormat(forBus: 0).settings 

     var audioFile = try AVAudioFile(forWriting: url, settings: settings) 
     try audioFile.write(from: buffer) 

    } catch let error as NSError { 
     print("ERROR HERE", error.localizedDescription) 
    } 

所以,我想我該轉換floatChannelData的錯誤或錯誤的一切。任何建議或指針在哪裏閱讀關於它會很好!

回答

3

隨着我們已經成功地得到它的工作有很大的幫助同事。顯然,AudioPCMBuffer也灌裝後需要被通知關於它的新的大小。 此外,我用完全錯誤的格式。

下面是代碼:

let SAMPLE_RATE = Float64(16000.0) 

let outputFormatSettings = [ 
    AVFormatIDKey:kAudioFormatLinearPCM, 
    AVLinearPCMBitDepthKey:32, 
    AVLinearPCMIsFloatKey: true, 
    // AVLinearPCMIsBigEndianKey: false, 
    AVSampleRateKey: SAMPLE_RATE, 
    AVNumberOfChannelsKey: 1 
    ] as [String : Any] 

let audioFile = try? AVAudioFile(forWriting: url, settings: outputFormatSettings, commonFormat: AVAudioCommonFormat.pcmFormatFloat32, interleaved: true) 

let bufferFormat = AVAudioFormat(settings: outputFormatSettings) 

let outputBuffer = AVAudioPCMBuffer(pcmFormat: bufferFormat, frameCapacity: AVAudioFrameCount(buff.count)) 

// i had my samples in doubles, so convert then write 

for i in 0..<buff.count { 
    outputBuffer.floatChannelData!.pointee[i] = Float(buff[i]) 
} 
outputBuffer.frameLength = AVAudioFrameCount(buff.count) 

do{ 
    try audioFile?.write(from: outputBuffer) 

} catch let error as NSError { 
    print("error:", error.localizedDescription) 
} 
+0

喜zo_chu如果以WAV文件轉換,同時完成錄音後...目前後,我停止記錄將文件轉換我可以錄製格式M4A然後我想知道以wav格式。 IM尋找wav格式感謝 –

+0

@ChinchanZu嗨直接記錄,以及我直接寫爲WAV和它的作品就像一個魅力。示例中的Url導致一個wav文件。 –