2017-02-11 9 views
1

私は今この流れがあります:私はAudioEngineでオーディオを録音し、それをオーディオ処理ライブラリに送り、オーディオバッファを取り戻してから、私はそれに書き込む意志があります。 wavファイルですが、私はそれをすばやく行う方法を完全に混乱させています。私は別のstackoverflowの答えから、このスニペットを試してみたが、それは空で、破損したファイルを書き込みsweatのwavオーディオファイルにfloatの配列を書き込む

。(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形式に変換します。私は直接wav形式で録音を探しています。 –

+0

@ChinchanZuこんにちは、私はwavに直接書き込み、それは魅力のように動作します。この例のUrlはwavファイルにつながります。 –

関連する問題