Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用AVPlayer时防止背景音频静音_Ios_Objective C_Audio_Avfoundation_Avplayer - Fatal编程技术网

Ios 使用AVPlayer时防止背景音频静音

Ios 使用AVPlayer时防止背景音频静音,ios,objective-c,audio,avfoundation,avplayer,Ios,Objective C,Audio,Avfoundation,Avplayer,我正在使用AVPlayer实例播放视频,我希望能够在播放视频时继续收听背景音乐 如果任何后台应用程序正在播放音乐,则每当我在AVPlayer上调用play,音乐都会静音。如何防止背景音频被静音 以下是我创建和启动AVPlayer的方法: AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil]; AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset

我正在使用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];

我可以通过在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播放另一首歌曲,它将中断我的背景播放,这是我想要的行为。

Ron Allan answer不幸不适合我,但它为我指明了正确的方向。我需要使用的是
AVAudioSessionCategoryAmbient
类别

这就是我的工作原理(在AppDelegate.swift中):


成功了。但是很难发现问题是否与AVPlayerI无关,因为我遇到了同样的问题,所以我知道应该去哪里。很高兴你把问题解决了。这就是我一直在寻找的答案。我可以在我的应用程序中通过视频和音频播放spotify音乐。但是,我更喜欢使用AVAudioSessionCategoryOptionDuckOthers而不是AVAudioSessionCategoryPlayback。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Don't mute the audio playback
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    } catch {}
    return true
}