Using HTML5’s Canvas and Audio Elements For A Guitar Tuning Mobile Application

David Pitt Development Technologies, HTML5, Keyhole Creations, Mobile 4 Comments

Attention: The following article was published over 11 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

I like to noodle around with my guitar, and I like to noodle around with HTML5. So, I thought I’d combine the two interests by creating an HTML5 guitar tuning mobile application that uses the <audio> and <canvas> tags. Before I get into the technical specifications, let me describe how the application functions.

It is a mobile web app that can be accessed with the following URL: http://guitar.keyholekc.com

The initial user interface is a jQuery mobile listview that displays a list of popular guitar tunings, as shown in the screen shot below:

When users select a Tuning option, a picture of one of my guitars fretboard appears. Notes for the Tuning are drawn over the respected string. Touching a string will play the note for tuning.

A tuning screen shot is shown below:

Let’s get into the HTML5 technical specifics.

The application is built using the MVC Backbone framework, so make sure to checkout our blog link for more details on Backbone. The Tuning list is obtained from JSON endpoints using the khsSherpa Java JSON/Endpoint framework. To get more information on Sherpa, check out its Github site here.  

The application utilizes the HTML5 <canvas> tag to display a fret.png and resize to a desired size. The <canvas> element definition is shown below:

<canvas id="canvas" style="display:inline;" width="180" height="240">
</canvas>

The Canvas element essentially provides a second and third drawing surface in the browser that can be “drawn upon” with a JavaScript API. Using jQuery’s On Load function, the fret.png is both assigned to an Image object (with the JavaScript shown below) and a function to call when the image is loaded.

	$(document).ready(function() {

	    img = new Image();
		img.src = "fret2.png";
		img.onload = fretImageLoaded;

	});

When loaded, the image is resized and added to <canvas> area. Also, a touch event is added to pay the note for a string that has been touched. JavaScript for this is shown below:

function fretImageLoaded() {

    var canvas = $("#canvas")[0];
    var ctx = canvas.getContext("2d");

    var ratio = 1.5;
    var imgWidth=img.width * ratio;
    var imgHeight=img.height * ratio;
    ctx.canvas.width= imgWidth;
    ctx.canvas.height=imgHeight;
    ctx.drawImage(img,0,0,imgWidth,imgHeight);
    ctx.font = "bold 32px Arial";

    // _underscore template variable
    var notes = <%=notes%>";
    var list = notes.split(",");
    var strings = [11,56,107,154,203,248];

    for (i = 0;i < strings.length;i++) {
        var x = strings[i]-9;
        var y = 150 - 32;
        ctx.fillStyle = "green";

        stringLabel(list[i].toUpperCase(),strings[i],"white",ctx);
    }

    $("#canvas").click(function(e) {
        var offsetX = e.pageX - $(this).position().left;
        var offsetY = e.pageY - $(this).position().top;

        for (i = 0;i < list.length;i=i+1) {
            var point = strings[i];
            if (offsetX >= point-5 && offsetX <= point + 20 ) {

                if (stringPlaying == i) {
                    stringLabel(list[i].toUpperCase(),strings[i],"white",ctx);
                    stopPlay(stringPlaying);
                    stringPlaying = -1;
                    } else {
                    if (stringPlaying >=0 ) {
                        stringLabel(list[stringPlaying].toUpperCase(),strings[stringPlaying],"white",ctx);
                        stopPlay(stringPlaying);
                    }
                    stringLabel(list[i].toUpperCase(),strings[i],"red",ctx);
                    playString(i);

                }
            }
        }

    });

}

When each string is touched, a JavaScript function is invoked that will play an MP3 file assigned to the string. This is done by defining an <audio> tag with an id for each string (0..5). The audio tag element is shown below:

<audio id="<%=audioId%>" loop="loop">
			<source src="<%=audioFile%>" type="audio/mp3" />
				Your browser does not support this audio format.
	</audio>

The Audio tag specifies the loop attribute. The loop attribute will continuously play the source MP3, which is dynamically assigned by the Backbone.js template mechanism, when the page loads.

There’s also another property named “Controls” that can be specified that will display an audio UI. This allows users to start/stop and control playing of the audio file. Since this application controls the playing with JavaScript, the JavaScript code to play a string’s audio is shown below. It uses a jQuery selector to get an <audio> element, then invokes the play() method.

   function playString(s) {
	   var id = "#audio"+s;
	   var a = $(id)[0];
	   a.play();
	   stringPlaying = s;
   }

Complete source for this application can be found at https://github.com/in-the-keyhole/khs-guitar-tuner

Even though this is just a simple application, it hopefully provides you with some insight into the <canvas> and <audio> HTML5 elements.

I’ve been thinking about turning this into a native iPhone and Android application using PhoneGap, so make sure to subscribe to our blog (on the right sidebar) to keep up-to-date on its progress.

— David Pitt, [email protected]

0 0 votes
Article Rating
Subscribe
Notify of
guest

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments