8

我在 Swift 中通过 UDP 通过 CocoaAsyncSocket 发送音频时遇到问题。

首先我运行下面的代码开始监听 4444 UDP 端口。

vlc --demux=rawaud --rawaud-channels=1 --rawaud-samplerate=48000 udp://@:4444

之后,我在 iPad2 中运行我的应用程序并按下连接。

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
}

任何想法?

4

0 回答 0