AVAudioEngine到NSData - wav文件无法在服务器

时间:2016-10-07 09:18:49

标签: ios swift avaudioengine

我正在尝试使用AVAudioEngine录制音频。文件被录制并正确播放。但是,我还需要通过套接字将我在tap处理程序中收到的AVAudioPCMBuffer发送到我的服务器。我正在将AVAudioPCMBuffer转换为NSData并发送它。服务器正在接收它 - 但是文件在服务器上无法正常播放。我在将AVAudioPCMBuffer转换为NSData时丢失了一些东西,或者我的录音丢失了一些配置。

任何帮助都会受到赞赏。谢谢!

let audioEngine  = AVAudioEngine()
let inputNode = audioEngine.inputNode
let bus = 0

 try file = AVAudioFile(forWriting: URLFor("recording.wav")!, settings: audioEngine.inputNode!.inputFormatForBus(0).settings)


inputNode!.installTapOnBus(bus, bufferSize: 4096, format: inputNode!.inputFormatForBus(bus)) {
                (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in


  self.file?.writeFromBuffer(buffer)  
  self.socketio.send(self.toNSData(buffer))

}

 do{
    audioEngine.prepare()
    try audioEngine.start()
}
catch{
    print("catch")
}



func toNSData(PCMBuffer: AVAudioPCMBuffer) -> NSData {
    let channelCount = 1  // given PCMBuffer channel count is 1
    let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: channelCount)
    let ch0Data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameCapacity * PCMBuffer.format.streamDescription.memory.mBytesPerFrame))
    return ch0Data
}

0 个答案:

没有答案