Swift3 Microphone Audio Input - play without recor

2019-05-06 16:44发布

I am trying to play microphone audio input using swift3 without recording. 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. Any ideas or suggestions are appreciated. Thank you!

1条回答
Lonely孤独者°
2楼-- · 2019-05-06 16:55

You can do this with AVAudioEngine, although you will hear feedback:

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()
    }
}
查看更多
登录 后发表回答