3

I am trying to record audio using AVAudioEngine. The file gets recorded and plays correctly. However, I also need to send AVAudioPCMBuffer that I receive in the tap handler to my server via socket. I am converting AVAudioPCMBuffer to NSData and sending it. The server is receiving it - however the file doesn't play correctly on the server. Am I missing something while converting AVAudioPCMBuffer to NSData or is my recording missing some configuration.

Any help would be appreciated guys. Thanks!

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
}
Rahul Ahuja
  • 705
  • 1
  • 9
  • 16
  • 1
    I don't have an answer but just some thoughts on how to pinpoint where the error occurs. Can you verify in some way that your `toNSData` function is generating valid NSData? For instance...can you play from the data your self in the app? (just to try and determine whether the data you generate is valid and the server has a problem or whether the data you generate is in fact invalid) – pbodsk Oct 07 '16 at 09:25
  • I don't know how to play NSData :( The server doesn't have a problem as the same works for Android – Rahul Ahuja Oct 07 '16 at 09:30
  • You could use an `AVAudioPlayer` for that perhaps? (as described here: http://stackoverflow.com/questions/32510346/how-to-play-nsdata-from-core-data-in-avaudioplayer). I don't know if this helps you, I just thought it'd be a good idea to determine where the error occurs (is the data invalid or does something happen to it during transfer to the server) – pbodsk Oct 07 '16 at 09:39
  • 1
    I will try this. However, is someone has a better idea of why this doesn't work I would be grateful. – Rahul Ahuja Oct 07 '16 at 11:43

0 Answers0