How To Play Video/Audio File Using Javascript In Html5

This article will tell you how to embed video/audio files in the Html5 web page using javascript, it will also tell you how to control the video/audio including play, pause, load, stop, and show the playing progress status, .etc with examples.

1. How To Embed & Control Video/Audio File In Html5 Web Page.

1.1 Embed & Control Video Files In Html5 Web Page.

  1. Use the Html <video> tag to embed the video file in the web page like below. You can provide the attributes like id, controls .etc.
    <video id="video1" style="display:block;margin-top: 10px;" controls></video>
  2. You can specify the video file name with the file path to the <video> tag’s src attribute to play the video.
    <video id="video1" src="http://www.abc.com/test.mp4" style="display:block;margin-top: 10px;" controls></video>
  3. If your video has different format files, you can provide each format file in a child <source> tag of the <video> tag like below.
    <video id="video1" style="display:block;margin-top: 10px;" controls>
        <source src="test-movie.mp4" type="video/mp4">
        <source src="test-movie.ogg" type="video/ogg">
    </video>
  4. To play the video file, you can first get the video element in javascript by it’s id, then call the video object’s play() method to play it.
  5. Call the video object’s pause() method to pause it, and call the video object’s load() method to load the video file to the beginning.
  6. If you want to listen to and process the video file’s playing process events ( such as ended, error, timeupdate ), you can call the video element’s method addEventListener(event_name, process_function(){……}) to listen and process the events.
    videoElement.addEventListener("ended", function(){
    
            message = "Play video finish.";
            alert(message);
            outputElement.value = message;
    
        });
  7. You can see The Video Embed Element Page for a detailed introduction of the video tag’s attributes, events, etc.

1.2 Embed & Control Audio Files In Html5 Web Page.

  1. Use the Html <audio> tag to embed the audio file in the web page like below. You can provide the attributes like id, controls .etc also.
    <audio id="audio1" style="display:block;margin-top: 10px;" controls></audio>
  2. The other attributes & events are very similar to the Html <video> tag, you can go to The Embed Audio element page to see the detailed introduction.

2. Embed Video Audio File In Html5 Web Page Examples.

  1. In this example, you can input the video or audio file URL in the related input text box.
  2. Then you can click the Play, Pause, Stop button to process the video or audio file.
  3. When the video or audio file is playing, you can see the video or audio file playing process information in the status text area.
  4. When you click the Stop button, it will hide the Html video or audio element.
  5. This example contains 2 source files, html5-video-audio-example.html, html5-video-audio-example.js.
  6. html5-video-audio-example.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>How To Play Video Audio In Html5 Example</title>
    <script type="text/javascript" src="html5-video-audio-example.js" charset="utf-8"></script>
    </head>
    <body onload="initialize()">
    <h3>How To Play Video Audio In Html5 Example.</h3>
    
    <div style="display:block;margin-top: 10px;">
        <label>Input Video File URL:</label>
        <input type="text" id="videoFileURL"/>
        <input type="button" id="playVideoBtn" value="Play Video" onclick="playVideo(this)" />
        <input type="button" id="pauseVideoBtn" value="Pause Video" onclick="pauseVideo(this)" />
        <input type="button" id="stopVideoBtn" value="Stop Video" onclick="stopVideo(this)" />
    </div>
    <output id="output1" style="display:block;margin-top: 10px;"></output>
    <video id="video1" style="display:block;margin-top: 10px;" controls></video>
    
    <div style="display:block;margin-top: 10px;">
        <label>Input Audio File URL:</label>
        <input type="text" id="audioFileURL"/>
        <input type="button" id="playAudioBtn" value="Play Audio" onclick="playAudio(this)" />
        <input type="button" id="pauseAudioBtn" value="Pause Audio" onclick="pauseAudio(this)" />
        <input type="button" id="stopAudioBtn" value="Stop Audio" onclick="stopAudio(this)" />
    </div>
    <output id="output2" style="display:block;margin-top: 10px;"></output>
    <audio id="audio1" style="display:block;margin-top: 10px;" controls></audio>
    
    </body>
    </html>
  7. html5-video-audio-example.js.
    var videoElementId = 'video1';
    var videoFileURLId = 'videoFileURL';
    var playVideoBtnId = 'playVideoBtn';
    var pauseVideoBtnId = 'pauseVideoBtn';
    var stopVideoBtnId = 'stopVideoBtn';
    
    var audioElementId = 'audio1';
    var audioFileURLId = 'audioFileURL';
    var playAudioBtnId = 'playAudioBtn';
    var pauseAudioBtnId = 'pauseAudioBtn';
    var stopAudioBtnId = 'stopAudioBtn';
    
    var outputElementId = 'output1';
    
    function initialize(){
    
        initialize_video();
    
        initialize_audio();
        
    }
    
    
    function initialize_video(){
    
        videoElement = document.getElementById(videoElementId);
        videoElement.style.display = 'none';
    
        outputElement = document.getElementById(outputElementId);
        
        playVideoBtnElement = document.getElementById(playVideoBtnId);
        playVideoBtnElement.disabled = false;
    
        pauseVideoBtnElement = document.getElementById(pauseVideoBtnId);
        pauseVideoBtnElement.disabled = true;
    
        stopVideoBtnElement = document.getElementById(stopVideoBtnId);
        stopVideoBtnElement.disabled = true;
    
        // Add video play complete event listener.
        videoElement.addEventListener("ended", function(){
    
            message = "Play video finish.";
            alert(message);
            outputElement.value = message;
    
        });
    
        // Add video error event listener.
        videoElement.addEventListener("error", function(){
    
            var errorMessage = "";
    
            switch(video.error.code){
    
                case MediaError.MEDIA_ERR_ABORTED:
                    errorMessage = 'Download video is aborted.';
                    break;
                case MediaError.MEDIA_ERR_DECODE:
                    errorMessage = 'Decode downloaded video error.';
                    break;
                case MediaError.MEDIA_ERR_NETWORK:
                    errorMessage = 'Download video network error.';
                    break;
                case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
                    errorMessage = 'Downloaded video format is not supported.';
                    break;    
            }
    
            if(errorMessage != ''){
    
                alert(errorMessage);
    
            }
    
            outputElement.value = message;
    
        });
    
        // Add time update event listener.
        videoElement.addEventListener("timeupdate", function(){
    
            var videoPlayStatus = "Playing ";
            var videoPlayTime = videoElement.currentTime;
            var videoDuration = videoElement.duration;
            videoPlayStatus += Math.floor(videoPlayTime) + ' seconds / Total ' + Math.floor(videoDuration) +' seconds'
            
            outputElement.value = videoPlayStatus;
    
        });
    }
    
    function initialize_audio(){
    
        audioElement = document.getElementById(audioElementId);
        audioElement.style.display = 'none';
        outputElement = document.getElementById(outputElementId);
    
        audioElement.addEventListener("ended", function(){
    
            message = "Play audio finish.";
            alert(message);
            outputElement.value = message;
    
        });
    
        // Add time update event listener.
        audioElement.addEventListener("timeupdate", function(){
    
            var audioPlayStatus = "Playing ";
            var audioPlayTime = audioElement.currentTime;
            var audioDuration = audioElement.duration;
            audioPlayStatus += Math.floor(audioPlayTime) + ' seconds / Total ' + Math.floor(audioDuration) +' seconds'
                
            outputElement.value = audioPlayStatus;
        
        });
        
        playAudioBtnElement = document.getElementById(playAudioBtnId);
        playAudioBtnElement.disabled = false;
    
        pauseAudioBtnElement = document.getElementById(pauseAudioBtnId);
        pauseAudioBtnElement.disabled = true;
    
        stopAudioBtnElement = document.getElementById(stopAudioBtnId);
        stopAudioBtnElement.disabled = true;
    }
    
    function playVideo(src){
    
        // http://dev2qa.com/demo/media/play_video_test.mp4
        videoFileURLInput = document.getElementById(videoFileURLId);
    
        videoFileURLStr = videoFileURLInput.value;
    
        if('' == videoFileURLStr){
            alert('Please input video file URL first.');
        }else{
    
            videoElement = document.getElementById(videoElementId);
            videoElement.style.display = 'block';
            videoElement.src = videoFileURLStr;
            videoElement.play();
    
            outputElement = document.getElementById(outputElementId);
            outputElement.style.display = 'block';
    
            src.disabled = true;
    
            pauseVideoBtnElement = document.getElementById(pauseVideoBtnId);
            pauseVideoBtnElement.disabled = false;
    
            stopVideoBtnElement = document.getElementById(stopVideoBtnId);
            stopVideoBtnElement.disabled = false;
        }
    
    }
    
    function pauseVideo(src){
    
        videoElement = document.getElementById(videoElementId);
    
        btnText = src.value.toLowerCase();
    
        if(btnText == 'pause video'){
            videoElement.pause();
            src.value = 'Continue Video';
        }else if(btnText == 'continue video'){
            videoElement.play();
            src.value = 'Pause Video';
        }
    
    }
    
    
    function stopVideo(src){
    
        outputElement = document.getElementById(outputElementId);
        outputElement.style.display = 'none';
    
        videoElement = document.getElementById(videoElementId);
    
        videoElement.load();
    
        videoElement.style.display = 'none';
    
        src.disabled = true;
    
        pauseVideoBtnElement = document.getElementById(pauseVideoBtnId);
        pauseVideoBtnElement.disabled = true;
        pauseVideoBtnElement.value = 'Pause Video';
    
    
        playVideoBtnElement = document.getElementById(playVideoBtnId);
        playVideoBtnElement.disabled = false;
    
    }
    
    
    
    function playAudio(src){
    
        //https://dev2qa.com/demo/media/test.mp3
        audioFileURLInput = document.getElementById(audioFileURLId);
    
        audioFileURLStr = audioFileURLInput.value;
    
        if('' == audioFileURLStr){
            alert('Please input audio file URL first.');
        }else{
    
            audioElement = document.getElementById(audioElementId);
            audioElement.style.display = 'block';
            audioElement.src = audioFileURLStr;
            audioElement.play();
    
            outputElement = document.getElementById(outputElementId);
            outputElement.style.display = 'block';
    
            src.disabled = true;
    
            pauseAudioBtnElement = document.getElementById(pauseAudioBtnId);
            pauseAudioBtnElement.disabled = false;
    
            stopAudioBtnElement = document.getElementById(stopAudioBtnId);
            stopAudioBtnElement.disabled = false;
        }
    
    }
    
    
    function pauseAudio(src){
    
        audioElement = document.getElementById(audioElementId);
    
        btnText = src.value.toLowerCase();
    
        if(btnText == 'pause audio'){
            audioElement.pause();
            src.value = 'Continue Audio';
        }else if(btnText == 'continue audio'){
            audioElement.play();
            src.value = 'Pause Audio';
        }
    
    }
    
    
    function stopAudio(src){
    
        outputElement = document.getElementById(outputElementId);
        outputElement.style.display = 'none';
    
        audioElement = document.getElementById(audioElementId);
    
        audioElement.load();
    
        audioElement.style.display = 'none';
    
        src.disabled = true;
    
        pauseAudioBtnElement = document.getElementById(pauseAudioBtnId);
        pauseAudioBtnElement.disabled = true;
        pauseAudioBtnElement.value = 'Pause Audio';
    
    
        playAudioBtnElement = document.getElementById(playAudioBtnId);
        playAudioBtnElement.disabled = false;
    
    }

3. Example Demo Video.

  1. Below is this example demo video.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky