简体   繁体   中英

Swift3 Microphone Audio Input - play without record

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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