在从同一台 iPhone 录制音频时避免使用 iPhone 扬声器发出音频

问题描述 投票:0回答:1

我正在开发一个应用程序,该应用程序可以连续录制音频。其间,它还播放通过我们的服务器以 wav 格式获取的音频。

一切正常。音频正在录制,来自服务器的音频也通过扬声器播放。

问题:我不希望麦克风录制来自服务器的扬声器正在播放的音频。我尝试了几种解决方案,但每次播放服务器的音频时,它都会被iPhone麦克风录制。下面是我的实现。

`在ViewDidLoad()中

 self.recordingSession = AVAudioSession.sharedInstance()

do {
                try recordingSession.setCategory(AVAudioSession.Category.playAndRecord, mode: .videoRecording, options: .defaultToSpeaker)
                try recordingSession.setActive(true)
                recordingSession.requestRecordPermission() { [unowned self] allowed in
                    DispatchQueue.main.async {
                        if allowed {
                            self.startRecording()
                        } else {
                            // failed to record!
                        }
                    }
                }
            } catch {
                // failed to record!
   }

func startRecording() {
        fileName = getDocumentsDirectory().appendingPathComponent("recording.wav")

                let settings = [
                    AVFormatIDKey: Int(kAudioFormatLinearPCM),
                    AVSampleRateKey: 12000,
                    AVNumberOfChannelsKey: 1,
                    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
                ] as [String : Any]

                do{

                    audioRecorder = try AVAudioRecorder(url: fileName, settings: settings)
                    audioRecorder.delegate = self


                    if(audioRecorder.record(forDuration: 3 )) {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                            print("recording succesfull...")
                            if self.audioRecorder != nil {
                                self.audioRecorder.stop()
                                self.audioRecorder = nil
                            }
                        }
                    }

                }
                catch {
                    print ("failed...")
                }
    }

 func playSound(url: URL) {
      do {
          print("Play URL:", url)
          let data = try! Data(contentsOf: url)
          audioPlayer = try! AVAudioPlayer(data: data)
          audioPlayer.delegate = self
          audioPlayer.prepareToPlay()
          audioPlayer.volume = 1.0
          audioPlayer.play()
      } catch let error {
        print(error.localizedDescription)
      }
    }
avaudioplayer avaudiosession avaudiorecorder avaudiosessioncategory
1个回答
0
投票

你要找的是回声消除技术,在IOS中你应该使用AudioUnit(kAudioUnitSubType_VoiceProcessingIO)来分离扬声器和麦克风

© www.soinside.com 2019 - 2024. All rights reserved.