Swift -如何在录制时忽略系统音频?

velaa5lx  于 2023-09-30  发布在  Swift
关注(0)|答案(1)|浏览(130)

我有一个AVAudioRecorder,可以录制音频和录音时播放的音乐曲目。当我在没有耳机/耳机的情况下录音时,播放的音乐会被麦克风接收到,尽管我的音量很低。
我能以某种方式使录音机忽略播放的音乐吗?

func startRecordingAudio() {
        let settings = [
            AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
            AVSampleRateKey: 44100,
            AVNumberOfChannelsKey: 2,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]
        
        audioFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("audioRecorderTemp\(Date().timeIntervalSince1970)").appendingPathExtension("m4a")
        
        do {
            audioRecorder = try AVAudioRecorder(url: audioFileURL!, settings: settings)
            audioRecorder?.record()
        } catch {
            finishRecordingAudio(success: false)
        }
    }

    private func handleAudioSessionCategory(areHeadphonesConnected: Bool) {
        if areHeadphonesConnected {
            try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .videoRecording)
        } else {
            try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .mixWithOthers, .allowBluetooth])
        }
        
        try? AVAudioSession.sharedInstance().setActive(true)
    }
vvppvyoh

vvppvyoh1#

您面临的问题是因为您正在音频会话类别中使用.mixWithOthers选项。此选项允许将来自其他应用的音频(例如在后台播放的音乐)与您的应用的音频混合。如果要防止录音时麦克风拾取音乐,应删除.mixWithOthers选项。

private func handleAudioSessionCategory(areHeadphonesConnected: Bool) {
    if areHeadphonesConnected {
       try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .videoRecording)
    } else {
        try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
    }

    try? AVAudioSession.sharedInstance().setActive(true)
}

相关问题