Search code examples
iosaudiowkwebviewmpmusicplayercontrollermpnowplayinginfocenter

How can I get current audio URL playing inside my app from WKWebView?


I have a WKWebView and I am checking if audio is playing using

[[AVAudioSession sharedInstance] isOtherAudioPlaying] 

I tried to get some information about it using :

  [MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo]

but it was nil.

Then I tried:

 [[MPMusicPlayerController systemMusicPlayer] nowPlayingItem]

and it was also nil.

How can I get URL of current playing audio?


Solution

  • You need to subscribe on notification :

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

    And then do this inside method playerItemBecameCurrent

    -(void)playerItemBecameCurrent:(NSNotification*)notification {
    AVPlayerItem *playerItem = [notification object];
    if(playerItem == nil) return;
    // Break down the AVPlayerItem to get to the path
    AVURLAsset *asset = (AVURLAsset*)[playerItem asset];
    NSURL *url = [asset URL];
    NSString *path = [url absoluteString];}