简体   繁体   English

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

[英]Swift3 Microphone Audio Input - play without record

I am trying to play microphone audio input using swift3 without recording. 我正在尝试使用swift3播放麦克风音频输入而不录制。 I can record the audio with the following code: 我可以使用以下代码录制音频:

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()

and then play it back ultimately after picking up the recorded file with: 然后在拿起录制的文件后最终播放:

audioPlayerNode.play()

But I would like to skip the recording step and play directly from the microphone input to the audio out (in this case the player node). 但是我想跳过录音步骤直接从麦克风输入到音频输出(在这种情况下是播放器节点)。 It then functions like an actual microphone. 它的功能就像一个真正的麦克风。 Can I do this directly or does an interim file need to exist? 我可以直接执行此操作还是需要存在临时文件? I combed the AVFoundation documentation but I can't seem to get a handle on the direct route. 我梳理了AVFoundation文档,但我似乎无法掌握直接路由。 Any ideas or suggestions are appreciated. 任何想法或建议表示赞赏。 Thank you! 谢谢!

You can do this with AVAudioEngine , although you will hear feedback: 您可以使用AVAudioEngine执行此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()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM