当使用AVPLayer播放视频时,它会停止背景音乐ios

Zal*_*tel 9 ios avplayer swift

我正在播放视频AVPlayer,它会阻止iPhone的背景音乐.请帮我解决

let item1 = AVPlayerItem.init(URL: NSURL(string:path))
player = AVPlayer(playerItem: item1)
layer?.player = player;
player?.play()
Run Code Online (Sandbox Code Playgroud)

Gra*_*rks 32

我的电影是为了动画; 他们没有声音.为了让其他声音继续播放,在Swift:

    // None of our movies should interrupt system music playback.
    _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers)
Run Code Online (Sandbox Code Playgroud)

感谢Marcus Adams的原始答案.


Ile*_*esh 10

在 swift 4.2 请试试这个。

do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: .mixWithOthers)
        try AVAudioSession.sharedInstance().setActive(true)
   } catch {
        print(error)
   }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ams 8

使用允许混合的AVAudioSession类别,例如AVAudioSessionCategoryPlayback和添加AVAudioSessionCategoryOptionMixWithOthers.

来自文档:

  • AVAudioSessionCategoryOptionMixWithOthers

    将此会话中的音频与来自其他活动会话的音频混合.

    仅在会话类别为AVAudioSessionCategoryPlayAndRecord或AVAudioSessionCategoryPlayback时有效.(如果会话类别是AVAudioSessionCategoryAmbient,则隐含.)

    如果您在使用此选项时激活会话,则应用的音频不会中断来自其他应用(例如音乐应用)的音频.如果不使用此选项(或可隐式混合的类别),则激活会话将中断其他不可混合的会话.

    适用于iOS 6.0及更高版本.