Media Playback in Windows Store Apps

Introduction

Today we are going to learn how to create a Windows Store App for Media Playback using JavaScript. Windows 8 provides rich media format support through the HTML5 media element, i.e. the video tag and the audio tag, which are built using the Windows Media Foundation technologies.

This app's code demonstrates basic playback of various media formats through the video tag. You can test playback of each media fomat by clicking on the corresponding buttons below. You can also try to playback other media files (e.g. .wmv, .wma, .wav, etc.) you have on your system in the music and video libraries using the File Picker button.

To start the creation of the app, add two JavaScript pages by right-clicking on the js folder in the Solution Explorer and select Add > new item > JavaScript Page and then provide an appropriate name. In the same way, add one HTML page to your project.

playback-in-windows-store-app.jpg

Write the following code in default.html:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title>App</title>

    <link rel="stylesheet" href="//Microsoft.WinJS.1.0/css/ui-light.css" />

    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>

    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <link rel="stylesheet" href="/css/default.css" />

    <script src="/js/script1"></script>

    <script src="/js/default.js"></script>

</head>

<body role="application" style="background-color: lightsalmon">

    <center><div id="rootGrid">

         <div id="content">

            <h1 id="featureLabel"></h1>

            <div id="contentHost"></div>

        </div>

       </div></center>

</body>

</html>

Write the following code in default.js:
 

(function () {

    "use strict";

    var appTitle = "";

 

    var pages = [

        { url: "page.html" }

    ];

    function activated(eventObject) {

        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            eventObject.setPromise(WinJS.UI.processAll().then(function () {

                var url = WinJS.Application.sessionState.lastUrl || pages[0].url;

                return WinJS.Navigation.navigate(url);

            }));

        }

    }

    WinJS.Navigation.addEventListener("navigated", function (eventObject) {

        var url = eventObject.detail.location;

        var host = document.getElementById("contentHost");

        host.winControl && host.winControl.unload && host.winControl.unload();

        WinJS.Utilities.empty(host);

        eventObject.detail.setPromise(WinJS.UI.Pages.render(url, host, eventObject.detail.state).then(function () {

            WinJS.Application.sessionState.lastUrl = url;

        }));

    });

    WinJS.Namespace.define("App", {

        appTitle: appTitle,

        pages: pages,

        videoOnError: function (error) {

            switch (error.target.error.code) {

                case error.target.error.MEDIA_ERR_ABORTED:

                    App.displayError("You aborted the video playback.");

                    break;

                case error.target.error.MEDIA_ERR_NETWORK:

                    App.displayError("A network error caused the video download to fail part-way.");

                    break;

                case error.target.error.MEDIA_ERR_DECODE:

                    App.displayError("The video playback was aborted due to a corruption problem or because the video used features your browser did not support.");

                    break;

                case error.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:

                    App.displayError("The video could not be loaded, either because the server or network failed or because the format is not supported.");

                    break;

                default:

                    App.displayError("An unknown error occurred.");

                    break;

            }

        },

        displayStatus: function (msg) {

            WinJS.log && WinJS.log(msg, null, "status");

        },

        displayError: function (msg) {

            WinJS.log && WinJS.log(msg, null, "error");

        }

    });

    WinJS.Application.addEventListener("activated", activated, false);

    WinJS.Application.start();

})();


Write the following code in page.html:
 

<!DOCTYPE html>

<html>

<head>

    <title></title>

    <script src="/js/script.js"></script>

</head>

<body>

    <div data-win-control="App.pageInput">

        <button class="action" id="playMP4">

            MP4 (H.264, AAC)</button>

        <button class="action" id="playMP3">

            MP3</button>

        <button class="action secondary" id="playFromFile">

            File Picker</button>

        <button class="action secondary" id="playbackStop">

            Stop Video</button>

        <br />

        <br />

    </div>

    <div data-win-control="App.pageOutput">

        <video id="playbackVideo" style="position: relative; width: 50%;" poster="images/images.jpeg">

        </video>

    </div>

</body>

</html> 


Write the following code in script.js:
 

(function () {

    "use strict";

    var page = WinJS.UI.Pages.define("page.html", {

        ready: function (element, options) {

            WinJS.Utilities.query("#playMP4").listen("click", getStartVideoFuntion(""));

            WinJS.Utilities.query("#playMP3").listen("click", getStartVideoFuntion(""));

            WinJS.Utilities.query("#playFromFile").listen("click", playFromFile);

            WinJS.Utilities.query("#playbackStop").listen("click", playbackStop);

            WinJS.Utilities.query("#playbackVideo").listen("error", App.videoOnError);

        },

 

        unload: function () {

            playbackStop();

        }

    });

    function getStartVideoFuntion(src) {

        return function () {

            var vid = WinJS.Utilities.query("#playbackVideo")[0];

            App.displayError("");

            vid.src = src;

            vid.play();

        };

    }

    function playFromFile() {

        var currentState = Windows.UI.ViewManagement.ApplicationView.value;

        if (currentState === Windows.UI.ViewManagement.ApplicationViewState.snapped &&

            !Windows.UI.ViewManagement.ApplicationView.tryUnsnap()) {

            App.displayStatus("File picker cannot be used when application is in the snapped state.");

            return;

        }

        var vid = WinJS.Utilities.query("#playbackVideo")[0],

            Pickers = Windows.Storage.Pickers,

            picker = new Pickers.FileOpenPicker();

        picker.fileTypeFilter.append("*");

        picker.suggestedStartLocation = Pickers.PickerLocationId.videosLibrary;

        picker.pickSingleFileAsync().done(

            function (item) {

                if (item !== null) {

                    App.displayError("");

                    vid.src = URL.createObjectURL(item, { oneTimeOnly: true });

                    vid.play();

                }

            }

        );

    }

    function playbackStop() {

        var vid = WinJS.Utilities.query("#playbackVideo")[0];

        if (!vid.paused) {

            vid.pause();

        }

    }

})(); 


Write the following code in script1.js:
 

(function () {

    var pageOutput = WinJS.Class.define(

        function (element, options) {

            element.winControl = this;

            this.element = element;

            new WinJS.Utilities.QueryCollection(element)

                        .setAttribute("role", "region")

                        .setAttribute("aria-labelledby", "outputLabel")

                        .setAttribute("aria-live", "assertive");

            element.id = "output";

 

            this._addOutputLabel(element);

            this._addStatusOutput(element);

        }, {

            _addOutputLabel: function (element) {

                var label = document.createElement("h2");

                label.id = "outputLabel";

                label.textContent = "Output";

                element.parentNode.insertBefore(label, element);

            },

            _addStatusOutput: function (element) {

                var statusDiv = document.createElement("div");

                statusDiv.id = "statusMessage";

                element.insertBefore(statusDiv, element.childNodes[0]);

            }

        }

    );

    var currentpageUrl = null;

 

    WinJS.Navigation.addEventListener("navigating", function (evt) {

        currentpageUrl = evt.detail.location;

    });

 

    WinJS.log = function (message, tag, type) {

        var statusDiv = document.getElementById("statusMessage");

    };

    var pageSelect = WinJS.UI.Pages.define("/sample-utils/page-select.html", {

        ready: function (element, options) {

            var that = this;

            var selectElement = WinJS.Utilities.query("#pageSelect", element);

            this._selectElement = selectElement[0];

 

            App.pages.forEach(function (s, index) {

                that._addpage(index, s);

            });

 

            selectElement.listen("change", function (evt) {

                var select = evt.target;

                if (select.selectedIndex >= 0) {

                    var newUrl = select.options[select.selectedIndex].value;

                    WinJS.Navigation.navigate(newUrl).then(function () {

                        setImmediate(function () {

                            document.getElementById("pageSelect").setActive();

                        });

                    });

                }

            });

            selectElement[0].size = (App.pages.length > 5 ? 5 : App.pages.length);

            if (App.pages.length === 1) {

                selectElement[0].setAttribute("multiple", "multiple");

            }

        },

        _addpage: function (index, info) {

            var option = document.createElement("option");

            if (info.url === currentpageUrl) {

                option.selected = "selected";

            }

            option.text = (index + 1) + ") " + info.title;

            option.value = info.url;

            this._selectElement.appendChild(option);

        }

    });

    function activated(e) {

        WinJS.Utilities.query("#featureLabel")[0].textContent = App.sampleTitle;

    }

    WinJS.Application.addEventListener("activated", activated, false);

    WinJS.Namespace.define("App", {

        pageInput: pageInput,

        pageOutput: pageOutput

    });
 

})(); 


Output:

playback-in-windows-store-apps.jpg

Summary

In this article I described how to create a Windows Store App for media playback using JavaScript. I hope this article has helped you in understanding this topic. Please share it. If you know more about this, your feedback and constructive contributions are welcome.

Up Next
    Ebook Download
    View all
    Learn
    View all