Ad

Notify End Of Play From Objective C To Javascript WKWebkit AVPlayer

I am trying to get a notification passed from ObjC to JavaScript when my audio has finished playing.

I currently call Obj C to play audio like so (from JS):

window.webkit.messageHandlers.playLetter.postMessage(audioSrc);

On the ObjC side I have the following method:

- (void) userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)scriptMessage {

   if([scriptMessage.name isEqualToString:@“playLetter”]){
       _contentAudioPlayer = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:scriptMessage.body]];
       [_contentAudioPlayer play];

       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:_contentAudioPlayer.currentItem];
   }
}

and the notification center calls this method when the audio has ended playing:

- (void) playerItemDidReachEnd {
    NSLog(@"audio ended");
}

Which is successful each time the audio ends.

My question is:

How can I notify my JavaScript that the audio has ended? On the JS side, I need to "wait" for the end of the audio to carry on the intended course of action

If you need more info please let me know.

Thx in advance.

Ad

Answer

I created a custom event on the JavaScript side of my application and dispatched the event in the playerItemDidReachEnd method with evaluateJavaScript from the webView:

- (void) playerItemDidReachEnd {
   [_webView evaluateJavaScript:
    @“var event = new CustomEvent(‘letterplayed’, {\n”
    @” detail: {\n”
    @”     message: ‘letter audio had finished playing’,\n”
    @”     time: new Date(),\n”
    @” },\n”
    @” bubbles: true,\n”
    @” cancelable: true\n”
    @“});\n”
    @“window.dispatchEvent(event);”
              completionHandler:nil];
}
Ad
source: stackoverflow.com
Ad