我想配置 AVAudioSession 以便我可以录制带音频的视频并播放音乐应用程序(或任何其他产生声音的应用程序,通常是互联网 radio 应用程序)中的音乐
我这样配置 session :
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: .mixWithOthers)
try? AVAudioSession.sharedInstance().setActive(true, with: .notifyOthersOnDeactivation)
当我的录音应用程序运行时,我可以开始播放音乐应用程序中的音频并录制视频(也录制音频)。到目前为止一切顺利。
现在,我将录音应用置于后台。音乐应用程序继续播放。没事。但是,当我的应用程序从背景音乐应用程序返回时停止播放。我希望它继续下去。所以它在拍摄视频时基本上就像内置相机应用程序一样。有没有办法告诉系统我想让其他应用继续播放?
我几乎遇到了类似的问题,我花了一两天的时间来解决这个问题。
在我的例子中,我使用 AVCaptureSession
进行视频/音频录制,它具有名为 automaticallyConfiguresApplicationAudioSession
的属性。根据 Apple 文档
automaticallyConfiguresApplicationAudioSession: A Boolean value that indicates whether the capture session automatically changes settings in the app’s shared audio session.
The value of this property defaults to true, causing the capture session to automatically configure the app’s shared AVAudioSession instance for optimal recording
因此,如果我们手动设置AVAudioSession
,我们应该将此属性设置为SAI
,如下所示,
captureSession.automaticallyConfiguresApplicationAudioSession = false;
将此属性设置为 SAI
并手动设置适当的 AVAudioSession
类别已经解决了我的问题!希望它对您的情况也有帮助!
对您的代码的更多观察
- 不需要
.notifyOthersOnDeactivation
标志来激活音频 session 此标志仅在停用 Audio Session 时使用。也就是说,当您在 setActive(_:options:)
实例方法的 beActive 参数中传递一个值 SAI
时。所以下面的代码可以很好地激活一个 session 试试? AVAudioSession.sharedInstance().setActive(true)
默认情况下,AVAudioSessionCategoryPlayAndRecord
类别领先到非常低音量的背景声音。如果你想要正常的音量,需要使用选项 .defaultToSpeaker
Và .mixWithOthers
如下,
试试? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, 带: [.mixWithOthers, .defaultToSpeaker])
好的!那么我认为如果您已正确完成所有其他操作,它现在可以正常工作。
注意** 我已经创建了一个工作示例项目供您引用,您可以在GitHub Here 上找到它。
Tôi là một lập trình viên xuất sắc, rất giỏi!