简体   繁体   English

使用 AVAudioRecorder 录制后,AVAudioPlayer 不通过扬声器播放

[英]AVAudioPlayer NOT playing through speaker after recording with AVAudioRecorder

I'm working on an app that does audio recording and playback of recorded audio.我正在开发一个应用程序,它可以录制音频并播放录制的音频。 I'm using AVAudioSession to change the category to playAndRecord as well as passing it to defaultToSpeaker .我正在使用AVAudioSession将类别更改为playAndRecord并将其传递给defaultToSpeaker

My problem is , if I launch the app, play an earlier recording, it plays through the bottom (louder) speaker as I want it to and expected BUT if I launch the app and start recording a new memo then play it back, no matter what I do, it will always use the quieter (phone call) speaker that's next to front face camera.我的问题是,如果我启动应用程序,播放较早的录音,它会按照我的意愿通过底部(更响亮的)扬声器播放,但如果我启动应用程序并开始录制新的备忘录然后播放它,无论如何我所做的,它将始终使用前置摄像头旁边的更安静(电话)扬声器。 I need it to play from the louder speaker (actually all speakers if possible).我需要它从更大的扬声器播放(如果可能的话,实际上是所有扬声器)。

NOTE: I'm running iOS 14.2.1, my phone is set to silent mode (usually) though I tried other settings as well.注意:我正在运行 iOS 14.2.1,虽然我也尝试了其他设置,但我的手机设置为静音模式(通常)。 I'm testing on an iPhone 12. Ideally, I'm not really looking for a 3rd party SDK or library solution as I want the playback to be simple and done natively.我正在 iPhone 12 上进行测试。理想情况下,我并不是真的在寻找第 3 方 SDK 或库解决方案,因为我希望播放简单且原生完成。

This is how I set the audioSession in my viewModel (that's initialized from a viewController):这就是我在 viewModel 中设置 audioSession 的方式(从 viewController 初始化):

private func setupAudioSession() {
    do {
        let session = AVAudioSession.sharedInstance()
        try session.setCategory(.playAndRecord, options: [.defaultToSpeaker, .allowBluetooth])
        try session.setActive(true)
        session.requestRecordPermission({ [weak self] allowed in
            guard let self = self else { return }
            if allowed == false {
                self.settingsAlert?()
            }
        })
    } catch {
        debugPrint("error setting up AVAudioSession")
    }
}

This is how I do recording:我是这样记录的:

func startRecording() {
    guard let audioFileDir = getAudioFilePath(songId: songModel!.id) else { return }
    let audioURLString = audioFileDir.absoluteString + ".m4a"
    guard let audioURL = URL(string: audioURLString) else { return }
    let recordingSettings: [String: Any] = [
        AVFormatIDKey: Int(kAudioFormatLinearPCM),
        AVLinearPCMIsNonInterleaved: false,
        AVSampleRateKey: 44_100.0,
        AVNumberOfChannelsKey: isStereoSupported ? 2 : 1,
        AVLinearPCMBitDepthKey: 16
    ]
    do {
        audioRecorder = try AVAudioRecorder(url: audioURL, settings: recordingSettings)
        audioUrl = audioURL
        audioRecorder?.delegate = self
        audioRecorder?.prepareToRecord()
        audioRecorder?.record()
    } catch {
        audioRecorder = nil
        debugPrint("Problem recording audio: \(error.localizedDescription)")
    }
}

I even included some code from WWDC 2020 for stereo recording and that's what isStereoSupported does.我什至包含了一些来自 WWDC 2020 的用于立体声录制的代码,这就是 isStereoSupported 所做的。

And this is how I do playback这就是我播放的方式

do {
    if let data = songDoc?.data?.audioData {
        audioPlayer = try AVAudioPlayer(data: data)
    } else if let url = audioUrl {
        audioPlayer = try AVAudioPlayer(contentsOf: url)
    }
    audioPlayer?.delegate = self
    audioPlayer?.play()
    isPlaying = true
} catch {
    audioPlayer = nil
    debugPrint("playback error: \(error.localizedDescription)")
}

Of course I have tried adding things like:当然,我尝试添加以下内容:

try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)

as well as setting the AVAudioSession each time I play or record.以及每次播放或录制时设置 AVAudioSession 。 I've tried bunch of other similar things to fix this issue but nothing seems to work.我已经尝试了很多其他类似的事情来解决这个问题,但似乎没有任何效果。

You should set audio session mode to AVAudioSessionModeVideoRecording and set session category options to AVAudioSessionCategoryOptionDefaultToSpeaker您应该将音频 session 模式设置为 AVAudioSessionModeVideoRecording 并将 session 类别选项设置为 AVAudioSessionCategoryOptionDefaultToSpeaker

[session setMode:AVAudioSessionModeVideoRecording error:&e] [会话设置模式:AVAudioSessionModeVideoRecording 错误:&e]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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