iOS中的蓝牙语音

时间:2017-07-24 04:08:08

标签: ios core-bluetooth ios-bluetooth

我正在进行为期四天的研究,但我找不到任何解决方案,可以在两个iOS设备之间远程调用蓝牙。

我发现使用多种连接框架的两台iOS设备之间可以进行音频流传输,但这对我没有帮助。我希望通过蓝牙在两台设备之间进行实时语音聊天。

蓝牙语音是否有任何CO-DAC?

我的代码是:

     var engine = AVAudioEngine()
        var file: AVAudioFile?
        var player = AVAudioPlayerNode()
        var input:AVAudioInputNode?
        var mixer:AVAudioMixerNode?

override func viewDidLoad() {
        super.viewDidLoad()
        mixer = engine.mainMixerNode
        input = engine.inputNode  
        engine.connect(input!, to: mixer!, format: input!.inputFormat(forBus: 0))
}

@IBAction func btnStremeDidClicked(_ sender: UIButton) {
mixer?.installTap(onBus: 0, bufferSize: 2048, format: mixer?.outputFormat(forBus: 0), block: { (buffer: AVAudioPCMBuffer, AVAudioTime) in
            let byteWritten = self.audioBufferToData(audioBuffer: buffer).withUnsafeBytes {
                self.appDelegate.mcManager.outputStream?.write($0, maxLength: self.audioBufferToData(audioBuffer: buffer).count)
            }
            print(byteWritten ?? 0)
            print("Write")
        })
        do {
            try engine.start()
        }catch {
            print(error.localizedDescription)
        }
}

func audioBufferToData(audioBuffer: AVAudioPCMBuffer) -> Data {
        let channelCount = 1
        let bufferLength = (audioBuffer.frameCapacity * audioBuffer.format.streamDescription.pointee.mBytesPerFrame)

        let channels = UnsafeBufferPointer(start: audioBuffer.floatChannelData, count: channelCount)
        let data = Data(bytes: channels[0], count: Int(bufferLength))

        return data
    }

提前致谢:)

1 个答案:

答案 0 :(得分:2)

为什么MultipeerConnectivity对您没有帮助?这是通过蓝牙甚至wifi传输音频的好方法。

当你这样称呼时:

audioEngine.installTap(onBus: 0, bufferSize: 17640, format: localInputFormat) {
    (buffer, when) -> Void in

您需要使用类型为AVAudioPCMBuffer的缓冲区。然后,您需要将其转换为NSData并写入您将与对等方打开的outputStream:

data = someConverstionMethod(buffer)
_ = stream!.write(data.bytes.assumingMemoryBound(to: UInt8.self), maxLength: data.length)

然后在另一台设备上,您需要从流中读取并从NSData转换回AVAudioPCMBuffer,然后您可以使用AVAudioPlayer来播放缓冲区。

我之前已经做了很短的延迟。