I have a problem to send audio by CocoaAsyncSocket via UDP in swift.
First of all I run below code to start listening 4444 UDP port.
vlc --demux=rawaud --rawaud-channels=1 --rawaud-samplerate=48000 udp://@:4444
after that I run my application in iPad2 and press connect.
import UIKit
import CocoaAsyncSocket
import AVFoundation
class ViewController: UIViewController , GCDAsyncUdpSocketDelegate {
var avAudioEngine : AVAudioEngine?
@IBAction func btnAction(sender: UIButton) {
avAudioEngine = AVAudioEngine()
let input = avAudioEngine?.inputNode
let socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
do {
try socket.bindToPort(4445)
try socket.connectToHost("192.168.0.137",onPort : 4444)
try socket.beginReceiving()
input?.installTapOnBus(0, bufferSize: 2048, format: input?.inputFormatForBus(0), block: { (buffer : AVAudioPCMBuffer, timeE: AVAudioTime) -> Void in
socket.sendData(self.toNSData(buffer), withTimeout: 0, tag: 0)
})
avAudioEngine?.prepare()
try avAudioEngine?.start()
// with nc -l -u -p 4444 and uncomment below block I can get "someText"
//socket.sendData("someText\n".dataUsingEncoding(NSUTF8StringEncoding), withTimeout: 0, tag: 0)
// socket.close()
}
catch{
print("err")
}
}
//socket.sendData just accepts NSData, So I think that we must convert it to NSData!
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
}
Any Idea?