Introduction
This article walks you through the process of adding music to your HTML5/JavaScript project, and that is all that the article shows you.
Background
In many articles the code has classes and code that the developer is used to utilizing. This article is written to guide you in how to add music to an HTML5 program
that could be added to the Windows 8 Store, with a lot more work. It has one sound file and several lines of code that are overly commented.
For more information, see my blog at: http://aka.ms/devschool_music_javascript.
Using the code
Using the Audio
object in the HTML5 DOM, you get an easy way to add music and sounds to your
JavaScript based Windows 8 Store game or project.
HTML 5
But to get started you have to add a single line to your HTML5 default.html page:
<canvas id="canvas">
The word between the quotes can be whatever you want to name the canvas, and frankly it was likely a bad idea to use the word: canvas. But many examples do so,
and I just followed the practice.
JavaScript
These two variables are generated to hold the canvas object and the context object.
Information about the HTML5 DOM
The Audio
HTML5 tag (new to HTML5) information is included in the DOM single page (a long single page) document that can be found at:
In the case of the JavaScript code, the object is constructed using the code:
var musicGame = new Audio("filepath to sound");
Then the music uses one of the attributes on the object to loop the music:
musicGame.loop = true;
<html>
<head>
<meta charset="utf-8" />
<title>MusicStoreDemo10</title>
<link href="http://www.codeproject.com/Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet";/>
<script src="http://www.codeproject.com/Microsoft.WinJS.1.0/js/base.js"></script>
<script src="http://www.codeproject.com/Microsoft.WinJS.1.0/js/ui.js"></script>
<link href="http://www.codeproject.com/css/default.css" rel="stylesheet" />
<script src="http://www.codeproject.com/js/default.js"></script>
</head>
<body>
Content Goes Here
<canvas id="canvas">
</body>
</html>
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var canvas;
var ctx;
var musicGame = new Audio("/sounds/hydrogen.mp3");
musicGame.loop = true;
document.addEventListener("DOMContentLoaded", initialize, false);
function initialize() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
musicGame.play();
}
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
} else {
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
};
app.start();
})();
History
Initial version.