Swift3麦克风音频输入-无需录制即可播放 [英] Swift3 Microphone Audio Input - play without record

查看:263
本文介绍了Swift3麦克风音频输入-无需录制即可播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是我想跳过录音步骤,直接从麦克风输入播放到音频输出(在这种情况下为播放器节点).然后,它的功能就像实际的麦克风一样.我可以直接这样做还是需要一个临时文件?我梳理了AVFoundation文档,但似乎无法理解直接路线.任何想法或建议,表示赞赏.谢谢!

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!

推荐答案

您可以使用AVAudioEngine进行此操作,尽管您会听到反馈:

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

这篇关于Swift3麦克风音频输入-无需录制即可播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆