Archive for category FAQ

HTML5, The Audio Element

Adding audio to HTML documents has always been challenging. HTML requires you to use a plug-in for audio controls. An HTML plug-in could be described as software that runs embedded into, or “on top of”, your web browser. Before Flash dominated the market, the plug-ins you could use for this were Windows Media Player, QuickTime, and Real Audio. The problem with this was that not everybody had these plug-ins installed on their computer, and that goes for Flash as well. You often times had some text explaining which media player works best with the website and required users to download and install it themselves. If you were thorough, you would write some unnecessary JavaScript to try and determine the plug-in that would work best, and since each plug-in has its own way of doing certain things, it only made the procedure that much more of a “task”. Things change with HTML5.

HTML5 comes with its very own <audio> element. To have audio in your HTML5 document, you use the following code:

<audio src="audio_file.mp3"></audio>

If you want to give your users controls, such as play and pause, you need to specify the ‘controls’ boolean attribute. A boolean attribute doesn’t have a value, if it’s there, the value is true, and if it’s not there the value is false. If you’re coding an XHTML document, you could say controls=”controls”.

<audio controls src="audio_file.mp3"></audio>

If you want to auto-play your file, you can use the ‘autoplay’ attribute. If you don’t want to auto-play, but you know the file will be played at some point, you can buffer, or pre-load the file. Buffering will tell the browser to download the file, but not to play it yet. There are two attributes for buffering: ‘autobuffer’ and ‘preload’. ‘autobuffer’ is a boolean attribute, and therefore does not take any values, merely having it in your attribute list will turn on auto-buffering. But beware, Safari auto-buffers by default. The ‘preload’ attribute takes the following values: none, auto and metadata. Using preload=”none”, you can explicitly tell browsers not to buffer the audio, and in turn, not to download the audio file until the user’s ready to listen to it. If you have a site with multiple audio files on one page, allowing them to auto-buffer would consume a lot of unnecessary bandwidth.

<audio controls autobuffer src="audio_file.mp3"></audio>
 
OR
 
<audio controls preload="none" src="audio_file.mp3"></audio>

Easy, right? Almost perfect? Yep, almost. Unfortunately there are these things called patents, and while some audio formats are free to use and develop with, some are patent protected. The MP3 audio format is patent protected, while the M4A or AAC is patent encumbered. What this means to you is that every browser may not support the audio format you have. The audio element has an optional ‘child’ element called ‘source’. You can use it to specify various formats or even different URL locations for your audio track. The browser will use whichever one it finds that it supports or can play. The format of choice in the open-source realm is OGG Vorbis, .ogg files. FireFox and Opera support OGG but Safari does not. This means that you will most likely have to find yourself audio software that will convert between audio formats. Thankfully, many exist. This also means that you may need to upload multiple copies of your audio file to the web server.

The ‘source’ element has two attributes, ‘src’ and ‘type’. The ‘src’ attribute let’s you specify the URL to where the audio-file is located. The ‘type’ attribute is optional, it allows you to specify the audio format type for each file. If the ‘type’ attribute is not provided, the web browser will try to determine the file type on its own – most likely by fetching the header information from the URL. Other content that goes inside the audio element should be ignored by browsers which support it, but rendered by browsers that do not. This way you can provide a failsafe for those not supporting HTML5 or the HTML5 audio element.

<audio controls>
	<!-- specify file types with the source element -->
	<source src="audio_file.mp3" type="audio/mp3">
	<source src="audio_file.ogg" type="audio/ogg">
 
	<!-- display a flash player in unnsuported browsers -->
	<object type="application/x-shockwave-flash" data="media_player.swf?file=audio_file.mp3">
		<param name="movie" value="media_player.swf?file=audio_file.mp3">
 
		<!-- if flash isn't supported, display a link -->
		<a href="audio_file.mp3">Download the file</a>
	</object>
</audio>

Example

Here is an example that should fall back to using a custom Flash player I made, if your browser isn’t equipped with the HTML5 audio element. Enjoy the music!

Making Me Nervous, By: Brad Sucks:

VN:F [1.9.22_1171]
Rating: 8.8/10 (13 votes cast)
VN:F [1.9.22_1171]
Rating: +6 (from 8 votes)
Share/Save

3 Comments

Randomizing Javascript Arrays

An array in JavaScript is like a collection of data. When one variable usually stores one value, an array stores multiple values. Each value is associated with an index position, otherwise known as ‘array key’. If you would like to learn more about arrays and how they work, read this article: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

If an array were a deck of cards, one might say that we need to “shuffle the deck”. That’s exactly what we need to do in this situation, but it’s better referred to as “sorting the array”. We need to change the order that the array is sorted in. The Array data type is really an object in JavaScript, and like most objects, it comes pre-built with methods (functions) that we can take advantage of. One method of interest is ‘sort’.

The Array’s ‘sort’ method accepts a callback function as an argument and uses it to compare the data inside the array. A callback function is a reference to a function that can be executed at a later time in your code. This can be better referred to as a ‘compare function’, because that’s what it’s there for, to compare the data. When executed, the ‘compare function’ is passed two valus from the array. If the ‘compare function’ is not provided, the array will be sorted in alphabetical order. See this website for detailed information on the Array’s ‘sort’ method: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort.

The idea is, you compare the data that gets passed to the ‘compare function’ and return a numerical value. The array gets sorted based on the values you return. The values can be less than 0, greater than 0, or exactly 0. Each value has special importance for how the data gets sorted. So, basically, we need a random number that meets this definition. For this, we use Math.random().

Math.random() returns a random number between 0 and 1. This is almost perfect, but we miss an entire number range, less than 0. Since the value from Math.random() could be 0.12, or 0.5, or 1, or even 0, we can subtract 0.5 from it to include the negative numbers in our range, and we still have the possibility of getting 0 or a value greater than 0. And so we have the following code:

?View Code JAVASCRIPT
var my_array = ['one','two','three'];
 
my_array.sort(function(){
	return Math.round(Math.random()) - 0.5;
});

A Not So Shuffled Array

At a glance, this looks like it should be perfect for what we need. When observed more carefully, though, we find inconsistancies in how the items actually get shuffled. This is due to the way the ‘sort’ method actually works. It’s based off the Bubble Sort algorithm. The bubble sort says, if A < B and B < C then there's no need to compare A and C. Because of this, some items may not actually get shuffled, and we end up with a not so shuffled array.

Fisher-Yates Shuffle

In 1938, two men known as Ronald Fisher and Frank Yates, outlined a way to randomize a list of numbers. We refer to it now as, the Fisher-Yates Shuffle. This method was released in their book, Statistical tables for biological, agricultural and medical research, and was designed to be implemented using pencil and paper. The method worked like this:

  1. Write down the numbers from 1 to N
  2. Pick a random number, k, between one and the number of unstruck numbers remaining (inclusive)
  3. Counting from the low end, strike out the kth number not yet struck out, and write it down elsewhere.
  4. Repeat from step 2 until all the numbers have been struck out.

Knuth Shuffle

If you were going to code the Fisher-Yates Shuffle using JavaScript, you would most likely model it off what we know as the Knuth Shuffle. In 1964, Richard Durstenfeld modernized the Fisher-Yates Shuffle for computer use in his book, Communications of the ACM, volume 7. This modernization was made popular as the Knuth Shuffle, by Donald E. Knuth, in volume 2 of his book, The Art of Computer Programming.

This approach is a little more difficult to implement than using ‘sort’, but the results are worth it. It works by looping the array backwards, and each time through, swapping the current item with a random item. The range that it uses to generate a random number follows the rule, 0 <= random number <= current index. If given an array with 4 items, the 4th item in the array will be swapped with an item at index positions 0, 1, or 2. The 3rd item will be swapped with the item at index positions 0 or 1. The 2nd item won't actually be so random, it will swap with the item at index position 0, the first item. At this point, the first item may or may not have already been swapped. By the time the fourth iteration occurres, all of the items in the array should have been shuffled, so it only loops n - 1 times, where 'n' represents the amount of items in the array. Here's what it looks like in JavaScript. I've attached it to the Array's prototype object so that every array has access to it.

?View Code JAVASCRIPT
Array.prototype.randomize = function()
{
	var i = this.length, j, temp;
	while ( --i )
	{
		j = Math.floor( Math.random() * (i - 1) );
		temp = this[i];
		this[i] = this[j];
		this[j] = temp;
	}
}
 
var my_array = ['one','two','three'];
my_array.randomize();

Contrasted Example

View: Live Example.

VN:F [1.9.22_1171]
Rating: 9.6/10 (16 votes cast)
VN:F [1.9.22_1171]
Rating: +4 (from 4 votes)

1 Comment

Guess That Letter

Writing a guess-that-letter is almost exactly like writing Guess That Number, except instead of storing a numerical value, we store a character from A – Z. When the user guesses, we use the ascii value of the character to hint to the user, higher or lower.

?View Code JAVASCRIPT
var guess_ascii, guess_char, guess_tries = 0;
 
function RandomRange(low,high)
{
    return( Math.floor((high-low-1)*Math.random()) + low );
}
 
/* http://sharkysoft.com/tutorials/jsa/content/018.html */
function AsciiValue(c)
{
	// restrict input to a single character
	c = c.charAt (0);
 
	// loop through all possible ASCII values
	var i;
	for (i = 0; i < 256; ++ i)
	{
		// convert i into a 2-digit hex string
		var h = i . toString (16);
		if (h . length == 1)
			h = "0" + h;
 
		// insert a % character into the string
		h = "%" + h;
 
		// determine the character represented by the escape code
		h = unescape (h);
 
		// if the characters match, we've found the ASCII value
		if (h == c)
			break;
	}
	return i;
}
 
/**
* @desc Think of a number from 1 to x
* @param number range to guess within
**/
function GuessChar( num )
{
	guess_tries = 0;
	guess_range = num;
	guess_ascii = RandomRange(97,122);				// a is ascii char 97, z is ascii char 122
	guess_char = String.fromCharCode( guess_ascii );
}
 
function Guess( frm )
{
	var g = frm.guess1.value.toLowerCase();				// we are dealing with a-z not A-Z
	var ascii = AsciiValue(g);
 
	if ( ascii < 97 || ascii > 122 )
	{
		alert("Please insert a letter from A - Z.");
		return;
	}
 
	guess_tries += 1;
	status = "Tries: "+ guess_tries;
 
	if ( g == guess_char )
	{
		if ( guess_tries == 1 )
			alert("Correct!  You guessed it in 1 try!  Wow, good job!!");
		else
			alert("Correct!  You guessed it in "+ guess_tries +" tries!");
 
		GuessOver();
	} else if ( guess_tries >= 10 ) {
 
		alert("Sorry, time's up. The letter was: "+ guess_char);
		GuessOver();
	} else if ( ascii < guess_ascii )
		frm.hint.value = "No, guess higher.";
	else if ( ascii > guess_ascii )
 
		frm.hint.value = "No, guess lower.";
}
 
/**
* @desc Prompt to start the guessing game over
**/
function GuessOver()
{
	if ( !confirm('Would you like to play again?') )
	{
		alert("Thanks for playing!  :)");
		location.reload();
	} else {
		GuessChar();
		document.forms.form1.hint.value = "Enter your Guess.";
	}
}
 
// initialize the guessing game
GuessChar();

View: Open Source Copy


Guess That Letter

I'm thinking of a letter between A and Z. Try to guess it in less than 10 tries.



Guess:


VN:F [1.9.22_1171]
Rating: 6.8/10 (6 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

,

2 Comments

Guess That Number

Writing a guess-that-number script in javascript is notorious in low-level javascript classes. I can’t tell you how many times someone has approached me on IRC asking about, “how to make a guess that number script?”. Since I wrote it so many times, I figured I would post it here for the world to access.

Isn’t sharing fun?

?View Code JAVASCRIPT
var guess_num = 0, guess_range, guess_tries = 0;
 
/**
* @desc Think of a number from 1 to x
* @param number range to guess within
**/
function GuessNum( num )
{
	if ( isNaN(num) )
		throw "Invalid Number Provided For GuessNum()";
 
	guess_tries = 0;
	guess_range = num;
	guess_num = Math.floor(Math.random() * num) + 1;
}
 
function Guess( frm )
{
	var g = parseInt(frm.guess1.value);
 
	if ( isNaN(g) )
	{
		alert("Please insert a numerical value.");
		return;
	} else if ( g < 1 || g > guess_range ) {
		alert("You must select a number between 1 and "+ guess_range);
		return;
	}
 
	guess_tries += 1;
	status = "Tries: "+ guess_tries;
 
	if ( g == guess_num )
	{
		if ( guess_tries == 1 )
			alert("Correct!  You guessed it in 1 try!  Wow, good job!!");
		else
			alert("Correct!  You guessed it in "+ guess_tries +" tries!");
 
		GuessOver();
	} else if ( guess_tries >= 10 ) {
 
		alert("Sorry, time's up. The number was: "+ guess_num);
		GuessOver();
	} else if ( g < guess_num )
		frm.hint.value = "No, guess higher.";
	else if ( g > guess_num )
 
		frm.hint.value = "No, guess lower.";
}
 
/**
* @desc Prompt to start the guessing game over
**/
function GuessOver()
{
	if ( !confirm('Would you like to play again?') )
	{
		alert("Thanks for playing!  :)");
		location.reload();
	} else {
		GuessNum( 100 );
		document.forms.form1.hint.value = "Enter your Guess.";
	}
}
 
// initialize the guessing game
GuessNum( 100 );

View: Open Source Copy


Guess That Number

I'm thinking of a number between 1 and 100. Try to guess it in less than 10 tries.



Guess:


VN:F [1.9.22_1171]
Rating: 7.3/10 (3 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

,

No Comments