避免AVPlayer和UIWebView同时播放音乐

Han*_*ang 5 avfoundation ios avplayer

感谢您注意到这个问题.我正在使用单身人士在我的应用中播放音乐,通过AVPlayer这样的方式:

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];

AVURLAsset *musicAsset    = [[AVURLAsset alloc] initWithURL:url options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:musicAsset];

AVPlayer *player = [AVPlayer playerWithPlayerItem:_playerItem];

player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

[player play];  
Run Code Online (Sandbox Code Playgroud)

它工作正常.但我的应用程序有一些音乐页面(HTML5),因此用户也可以访问网页,并在那里播放音乐.来自UIWebView和来自的音乐AVPlayer可以在同一时间播放,似乎很奇怪.有没有办法检测是否UIWebView会播放音乐,所以我可以阻止原生音乐AVPlayer?谢谢!

hea*_*ger 2

您是否尝试过监听 AVPlayerItemBecameCurrentNotification?当您的网页启动媒体文件(视频或音频)时,该文件将被触发。您可以按如下方式拦截它:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(avPlayerItemBecameCurrent:)
                                             name:@"AVPlayerItemBecameCurrentNotification"
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

现在(我意识到我正在教你在这里吸鸡蛋 - 抱歉。这只是为了完整性)你需要 avPlayerItemBecameCurrent:

-(void)avPlayerItemBecameCurrent:(NSNotification*)notification
{
    // Your code goes here to stop your native AVPlayer from playing.
}
Run Code Online (Sandbox Code Playgroud)

警告 - 我还没有测试过这个,但它应该有效。

(写完这篇文章,并在进一步挖掘之后,我发现了这个Detecting and拦截视频播放 UIWebView