我正在使用AVPlayer实例播放视频,我希望能够在播放视频时继续收听背景音乐。
如果有任何后台应用播放音乐,只要我在AVPlayer上调用play
,音乐就会静音。如何防止背景音频静音?
以下是我创建和启动AVPlayer的方法:
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
[self.layer addSublayer:playerLayer];
// mutes all background audio
[player play];
答案 0 :(得分:1)
我能够通过在AppDelegate.swift类中执行以下操作来解决此问题:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
}
return true
}
我还证实,如果我开始通过iTunes播放另一首歌,它会中断我的后台播放,这就是我想要的行为。
答案 1 :(得分:0)
很遗憾,罗恩·艾伦的回答对我没有用,但是它为我指明了正确的方向。我需要使用的是AVAudioSessionCategoryAmbient
类别。
这对我有用(在AppDelegate.swift中):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Don't mute the audio playback
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
} catch {}
return true
}