HTML and CSS Reference
In-Depth Information
eXerCISe 8-4. ChaNGING the aUDIO SOUrCe
1.
Close the browser and stop the debugger.
2.
Create another audio file in both
.mp3
and
.ogg
formats and copy these to the
Chapter
8
\Media folder.
3.
In the Solution Explorer, right-click the Media folder and select the Add ➤ Existing
Item links. Navigate to the Chapter
8
\Media folder and select both the
.mp3
and
.ogg
files that you just encoded.
4.
open the
Index.cshtml
file. At the top of the existing
script
element, declare the
following variable. This will be used to keep track of how many songs were played.
var songCount=0;
5.
Add the following code shown in bold to the
endAudio()
function. If the audio clip
that just finished is the first one, the code will change the
src
attribute to reference
the second file. The file is then loaded and played. (Note, you'll need to change these
filenames to use the actual files that you included in your project.)
function endAudio() {
document.getElementById("play").value = "Play";
document.getElementById("audioSeek").value = 0;
document.getElementById("duration").innerHTML = "0/" + Math.
round(audio.duration);
if (++songCount < 2) {
document.getElementById("oggSource").src="/Media/Sample.ogg";
document.getElementById("mp3Source").src="/Media/Sample.mp3";
audio.load();
audio.play();
}
}
6.
Save your changes and press F5 to debug the application. The initial song should
start playing.
7.
To save some time, fast-forward the clip to almost the end of the file and then wait
for it to finish. The second file should automatically start playing. You should notice
the span control was updated to show the duration of the second file.
Detecting Audio Support
You can programmatically determine if a source is supported by the browser by calling the
canPlayType()
method on the
audio
element, passing in the
type
attribute. To demonstrate this, add the following code to the
beginning of the
script
block, after the
audio
variable declaration:
var sources=audio.getElementsByTagName("source");
for (var i=0; i<sources.length; i++) {
alert("[" + sources[i].type + "] - " + audio.canPlayType(sources[i].type));
}