在Swift中使用蓝牙耳机的麦克风和内置扬声器进行录制和播放

时间:2020-03-30 22:30:57

标签: ios swift audio bluetooth avfoundation

我目前有一对蓝牙耳塞。从这篇文章中,我获得了从蓝牙耳塞的麦克风中检索音频,然后通过蓝牙耳塞播放音频所需的代码。但是,我想修改代码,以便可以从蓝牙耳塞的麦克风中检索音频,然后通过电话的INTERNAL扬声器/通过可能与电话物理连接的任何其他耳塞播放音频。我将如何去做?这是我当前的代码:

import UIKit
import AVFoundation

class PlayRecordVC: UIViewController, AVAudioRecorderDelegate {

    let audioSession = AVAudioSession.sharedInstance()
    let player = AVAudioPlayerNode()
    let engine = AVAudioEngine()

    override func viewDidLoad() {
        super.viewDidLoad()

        do{
            try audioSession.setCategory(.playAndRecord, mode: .default, options: [.allowBluetooth])
            try audioSession.overrideOutputAudioPort(.speaker)
            try audioSession.setActive(true)
        } catch{
            print(error.localizedDescription)
        }
        let input = engine.inputNode

        engine.attach(player)

        let bus = 0
        let inputFormat = input.inputFormat(forBus: bus)

        engine.connect(player, to: engine.mainMixerNode, format: inputFormat)

        input.installTap(onBus: bus, bufferSize: 512, format: inputFormat) { (buffer, time) -> Void in
            self.player.scheduleBuffer(buffer)
            print(buffer)
        }
    }

    @IBAction func start(_ sender: UIButton) {
        try! engine.start()
        player.play()
    }

    @IBAction func stop(_ sender: UIButton) {
        engine.stop()
        player.stop()
    }

}

更新:

当我添加audioSession.overrideOutputAudioPort(.speaker)行时,根本没有音频播放(既不是蓝牙耳塞也不是手机的内置扬声器)

2 个答案:

答案 0 :(得分:1)

我还没有测试这是否实际上会使耳机仍然使用麦克风,但是默认情况下,将音频路由到扬声器而不是耳机,这应该可行:

try! audioSession.overrideOutputAudioPort(.speaker)  

这里是方法的documentation

您还可以使this category option的音频会话具有相同的效果,但也避免通过手势(例如,安装新耳机)将其重置。

如果在测试后发现实际上还可以移动录音以使用内部麦克风,我认为没有其他方法(至少我没有发现其他方法)。

答案 1 :(得分:1)

let audioSession = AVAudioSession.sharedInstance()
do {

    try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .allowBluetooth)
    try audioSession.setMode(AVAudioSessionModeDefault)
    try audioSession.setActive(true)
} catch {
print(error)
}

我需要定义正确的模式。 不完全确定哪种模式最适合您的情况。 https://developer.apple.com/documentation/avfoundation/avaudiosession/mode

下面的此链接具有扩展名,可用于检查是否已插入麦克风。 https://stackoverflow.com/a/52460651/8272698