Search code examples
javascriptpopcornjs

How can I stop a media from playing in popcron.js


I have and audio that is being played and I want to stop it from playing once the user clicks on a button. I have tried popcorn.mute(), but it does not give the result I want. I want something like popcorn.stop();


Solution

  • If you want to really destroy the video, you need to make sure that a) it's not playing and b) there are no references to it anywhere in memory, including the DOM. That way, the Javascript engine can garbage-collect it. Just to be extra thorough, we'll clear out the src.

    var video = popcorn.media; //grab a reference to the actual video element
    
    //make sure it's not playing
    video.pause();
    
    //clean up popcorn
    popcorn.destroy();
    popcorn.media = null; //popcorn should probably do this in destroy, but it doesn't
    
    //clear the src, Make sure it's no longer using the network.
    video.src = '';
    video.load();
    
    //remove from the DOM. You won't see it anymore.
    if (video.parentNode) {
        video.parentNode.removeChild(video);
    }
    

    You'll also want to clear any other references you may have to the video, and it probably couldn't hurt to remove any event listeners you may have added, whether directly on the video element or through Popcorn.