Swift3麦克风音频输入-无录制播放

5

我正在尝试使用Swift3播放麦克风音频输入,而不进行录制。 我可以使用以下代码记录音频:

let session = AVAudioSession.sharedInstance()
    try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)

    try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
    audioRecorder.delegate = self
    audioRecorder.isMeteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()

然后,在使用以下方法获取录制文件后进行播放:

audioPlayerNode.play()

但是我想跳过录制步骤,直接从麦克风输入播放到音频输出(在这种情况下是播放器节点)。然后它就像一个实际的麦克风一样运作。我能直接做到这点吗?还是需要存在一个中间文件?我查阅了AVFoundation文档,但似乎找不到直接路线的方法。有任何想法或建议将不胜感激。谢谢!

1个回答

2
你可以使用AVAudioEngine来实现,但你会听到反馈声:
import AVFoundation

class ViewController: UIViewController {
    let engine = AVAudioEngine()

    override func viewDidLoad() {
        super.viewDidLoad()

        let input = engine.inputNode!
        let player = AVAudioPlayerNode()
        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
            player.scheduleBuffer(buffer)
        }

        try! engine.start()
        player.play()
    }
}

谢谢您的回复,这很有效,但是停止服务时很难避免崩溃。在引擎停止后,我需要对节点进行任何操作以实现可行的重新启动吗?谢谢。 - RandallShanePhD
你是如何停止和启动程序的?你遇到了什么样的崩溃? - Rhythmic Fistman
其实,我明白了。我的停止函数出现了错误。再次感谢你! - RandallShanePhD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接