Voice over bluetooth in iOS

心不动则不痛 提交于 2019-12-11 16:43:51

问题


I am doing research over four days, But I am not found any solution for calling over Bluetooth between two iOS devices within a distance.

I found that audio streaming is possible between two iOS devices using multipeer connectivity framework but this is not helpful for me. I want real time voice chat between two devices over Bluetooth.

Is there any CO-DAC for voice over Bluetooth?

My code is:

     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
    }

Thanks in Advance :)


回答1:


Why is MultipeerConnectivity not helpful for you? It is a great way to stream audio over bluetooth or even wifi.

When you call this:

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

You need to use the buffer, which has type AVAudioPCMBuffer. You then need to convert that to NSData and write to the outputStream that you would've opened with the peer:

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

Then on the other device you need to read from the stream and convert from NSData back to an AVAudioPCMBuffer, and then you can use an AVAudioPlayer to playback the buffer.

I have done this before with a very minimal delay.



来源:https://stackoverflow.com/questions/45272471/voice-over-bluetooth-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!