Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid AVPlayer and UIWebView play music in the same time

Thanks for noticing this question. I am using a singleton to play music in my app, via AVPlayer, like this way:

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];  

It works fine. But my app has some music pages(HTML5), so user can also visit the web page, and play music there. The music from UIWebView and from AVPlayer can be played in the same time, seems to be very strange. Is there any ways to detecting if UIWebView will playing music, so I can stop the native AVPlayer? Thanks!

like image 633
Hang Avatar asked Nov 02 '22 06:11

Hang


1 Answers

Have you tried listening for AVPlayerItemBecameCurrentNotification? When your webpage launches a media file (video or audio), this will be fired. You can intercept it as follows:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(avPlayerItemBecameCurrent:)
                                             name:@"AVPlayerItemBecameCurrentNotification"
                                           object:nil];

Now (and I realise I'm teaching you to suck eggs here - my apologies. This is just for completeness) you need avPlayerItemBecameCurrent:

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

Caveat - I haven't tested this, but it should work.

(Having written this, and after digging around a little more, I found this Detecting and intercepting video playback in UIWebView)

like image 83
headbanger Avatar answered Nov 11 '22 15:11

headbanger