Reader Level:
Article

Media Player Events in Windows Store Apps

By Deepak Middha on Nov 08, 2012
In this app I described Media events in Windows Store Apps using JavaScript.

Introduction

In this article I describe how to create a Windows Store App for a Media event using JavaScript. This scenario demonstrates how to register for media events from hardware media transport controls

I assume you can create a simple Windows Store App using JavaScript. For more help visit Simple Windows Store Apps using JavaScript.

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

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.js"></script>

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

</head>

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

    <div id="rootGrid">

        <center><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

    });

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

    WinJS.Application.start();

})();


Write the following code in page.html:
 

<!DOCTYPE html>

<html>

<head>

    <title></title>

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

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

</head>

<body>

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

        <button id="button1">Select</button>

        <br />

        <br />

    </div>

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

        <audio id="audiotag" controls="controls" msaudiocategory="backgroundcapablemedia" />

        <img id="albumart" />

    </div>

</body>

</html> 


Write the following code in script.js:
 

(function () {

    "use strict";

    var mediaControls;

    var currentSongIndex = 0;

    var playlist = [];

    var playlistCount;

    var nextRegistered = false;

    var previousRegistered = false;

    var thumbnailName = null;

    function song() {

        this.URLObject;

        this.file;

    }

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

        ready: function (element, options) {

            document.getElementById("button1").addEventListener("click", doSomething1, false);

            mediaControls = Windows.Media.MediaControl;

            mediaControls.addEventListener("playpausetogglepressed", playPause, false);

            mediaControls.addEventListener("playpressed", play, false);

            mediaControls.addEventListener("stoppressed", stop, false);

            mediaControls.addEventListener("pausepressed", pause, false);

            mediaControls.addEventListener("fastforwardpressed", fastForward, false);

            mediaControls.addEventListener("rewindpressed", rewind, false);

            mediaControls.addEventListener("channeluppressed", channelUp, false);

            mediaControls.addEventListener("channeldownpressed", channelDown, false);

            mediaControls.addEventListener("recordpressed", record, false);

            id("audiotag").addEventListener("playing", playing, false);

            id("audiotag").addEventListener("pause", paused, false);

            id("audiotag").addEventListener("ended", songEnded, false);

            mediaControls.isPlaying = false;

        }

    });

    function id(elementId) {

        return document.getElementById(elementId);

    }

    function createPlaylist(files) {

        var file;

        if (files.size > 0) {

            playlistCount = files.size;

            if (nextRegistered) {

                mediaControls.removeEventListener("nexttrackpressed", nextTrack, false);

                nextRegistered = false;

            }

            if (previousRegistered) {

                mediaControls.removeEventListener("previoustrackpressed", previousTrack, false);

                previousRegistered = false;

            }

            currentSongIndex = 0;

            playlist = [];

            if (playlistCount > 1) {

                if (!nextRegistered) {

                    mediaControls.addEventListener("nexttrackpressed", nextTrack, false);

                    nextRegistered = true;

                }

            }

            for (var fileIndex = 0; fileIndex < files.size; fileIndex++) {

                var tempSong = new song;

 

                file = files[fileIndex];

                tempSong.URLObject = URL.createObjectURL(file, { oneTimeOnly: false });

                tempSong.file = file;

                playlist[fileIndex] = tempSong;

            }

        }

 

    }

    function setCurrentPlaying(index) {

        id("audiotag").src = playlist[index].URLObject;

        if (mediaControls.isPlaying === true) {

            id("audiotag").play();

        }

        setMetaData(index);

    }

    function setMetaData(songIndex) {

        try {

            var thumbnailMode = Windows.Storage.FileProperties.ThumbnailMode.musicView;

            var thumbnailOptions = Windows.Storage.FileProperties.ThumbnailOptions.ResizeThumbnail;

            var file = playlist[songIndex].file;

            file.getThumbnailAsync(thumbnailMode, 96, thumbnailOptions).done(function (thumbnail) {

                if (thumbnail) {

                    var inputStream = thumbnail.getInputStreamAt(0);

                    var reader = new Windows.Storage.Streams.DataReader(inputStream);

                    var size = thumbnail.size;

                    if (size > 0) {

                        reader.loadAsync(size).done(function () {

                            var buffer = new Array(size);

                            reader.readBytes(buffer);

                            thumbnail.close();

                            reader.close();

                            var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;

                            if (thumbnailName === null || thumbnailName === "thumbnail2.jpg") {

                                thumbnailName = "thumbnail.jpg";

                            } else {

                                thumbnailName = "thumbnail2.jpg";

                            }

                            tempFolder.createFileAsync(thumbnailName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (imageFile) {

                                Windows.Storage.FileIO.writeBytesAsync(imageFile, buffer).done(function () {

                                    playlist[songIndex].file.properties.getMusicPropertiesAsync().done(function (musicProperties) {

                                        setAlbumArt(thumbnailName, musicProperties);

                                    });

                                });

                            });

                        });

                    } else {

                        WinJS.log("Thumbnail is empty", "app", "error");

                        thumbnail.close();

                        reader.close();

                        inputStream.close();

                    }

                } else {

                    WinJS.log(getTimeStampedMessage("Song Art Work not available for " + storageFile.path), "app", "error");

                    mediaControls.albumArt = "";

                }

            });

        } catch (ex) {

            WinJS.log("Error in GetThumbnail(): " + ex.description, "app", "error");

        }

    }

    function setAlbumArt(fileName, musicProperties) {

        try {

            var uri = new Windows.Foundation.Uri("ms-appdata:///temp/" + fileName);

            mediaControls.albumArt = uri;

            mediaControls.trackName = musicProperties.title;

            mediaControls.artistName = musicProperties.artist;

        } catch (ex) {

            WinJS.log("Error in setAlbumArt(): " + ex, "app", "error");

        }

    }

    function doSomething1() {

        var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

        openPicker.fileTypeFilter.replaceAll([".mp3", ".mp4", ".wma", ".m4a"]);

        openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;

 

        openPicker.pickMultipleFilesAsync().done(function (files) {

            if (files.length > 0) {

                createPlaylist(files);

                setCurrentPlaying(currentSongIndex);

            }

        });

    }

    function getTimeStampedMessage(eventCalled) {

        var timeformat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

        var time = timeformat.format(new Date());

        var message = eventCalled + "\t\t" + time;

        return message;

    }

    function playing() {

        mediaControls.isPlaying = true;

    }

    function paused() {

        mediaControls.isPlaying = false;

    }

    function songEnded() {

        nextTrack();

    }

    function playPause() {

        if (mediaControls.isPlaying === false) {

            WinJS.log(getTimeStampedMessage("Play/Pause - Play Received"), "app", "status");

            id("audiotag").play();

        }

        else {

            WinJS.log(getTimeStampedMessage("Play/Pause - Pause Received"), "app", "status");

            id("audiotag").pause();

        }

    }

    function play() {

        WinJS.log(getTimeStampedMessage("Play Received"), "app", "status");

        id("audiotag").play();

    }

    function stop() {

        WinJS.log(getTimeStampedMessage("Stop Received"), "app", "status");

        id("audiotag").pause();

        id("audiotag").currentTime = 0;

    }

    function pause() {

        WinJS.log(getTimeStampedMessage("Pause Received"), "app", "status");

        id("audiotag").pause();

    }

    function nextTrack() {

        WinJS.log(getTimeStampedMessage("Next Track Received"), "app", "status");

        if (currentSongIndex < (playlistCount - 1)) {

            currentSongIndex++;

            setCurrentPlaying(currentSongIndex);

            if (currentSongIndex > 0) {

                if (!previousRegistered) {

                    mediaControls.addEventListener("previoustrackpressed", previousTrack, false);

                    previousRegistered = true;

                }

            }

            if (currentSongIndex === (playlistCount - 1)) {

                if (nextRegistered) {

                    mediaControls.removeEventListener("nexttrackpressed", nextTrack, false);

                    nextRegistered = false;

                }

            }

        }

    }

    function previousTrack() {

        WinJS.log(getTimeStampedMessage("Prev Track Received"), "app", "status");

        if (currentSongIndex > 0) {

            if (currentSongIndex === (playlistCount - 1)) {

                if (!nextRegistered) {

                    mediaControls.addEventListener("nexttrackpressed", nextTrack, false);

                    nextRegistered = true;

                }

            }

            currentSongIndex--;

 

            if (currentSongIndex === 0) {

                if (previousRegistered) {

                    mediaControls.removeEventListener("previoustrackpressed", previousTrack, false);

                    previousRegistered = false;

                }

            }

            setCurrentPlaying(currentSongIndex);

        }

    }

    function fastForward() {

        WinJS.log(getTimeStampedMessage("Fast Forward Received"), "app", "status");

    }

    function rewind() {

        WinJS.log(getTimeStampedMessage("Rewind Received"), "app", "status");

    }

    function channelUp() {

        WinJS.log(getTimeStampedMessage("Channel Up Received"), "app", "status");

    }

    function channelDown() {

        WinJS.log(getTimeStampedMessage("Channel Down Received"), "app", "status");

    }

    function record() {

        WinJS.log(getTimeStampedMessage("Record Received"), "app", "status");

    }

})(); 

Output:

 camer-function-in-windows-store-apps.jpg

Summary

In this app I described Media events in Windows Store Apps using JavaScript. I hope this article has helped you to understand this topic. Please share if you know more about this. Your feedback and constructive contributions are welcome.

Deepak Middha

Deepak Middha is one time Microsoft MVP(Client App Dev) , working as Sr. Software Developer with lots of hands on experience using ASP.NET 2.0/3.5, AJAX, MVC, C#,  SQL Server 2005/2008/2012, WCF, JQuery and Silverl... Read more

COMMENT USING