Swift3 Microphone Audio Input - Playback Without Recording

I am trying to play microphone audio input using swift3 without recording. I can record sound 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 eventually after collecting 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 output (in this case, the node player). Then it functions like a real microphone. Can I do this directly or do I need an intermediate file? I was combing the AVFoundation documentation, but I cannot figure out how to handle the direct route. Any ideas or suggestions are welcome. Thank!

+4
source share
1 answer

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()
    }
}
+2

Source: https://habr.com/ru/post/1675810/


All Articles