Passa al contingut principal

MP3 Player with HTML5 – lesson 2

MP3 Player with HTML5 - lesson 2

MP3 Player with HTML5. Lesson 2 – Controlling Play, Pause and Stop with Javascript



In the previous section we created an audio element using HTML5 and then controlled it using the built-in controls available through the browser. In most applications, however, you will want the user to have more control over the audio (or video) playback. The Javascript API associated with the audio (and video) element provides a robust set of commands for controlling and monitoring the media stream.


In this chapter, we’re going to move beyond the provided HTML5 controls and start using Javascript to control the audio playback.


If you haven’t used much Javascript before, let me talk a little bit about the language and its usage. First, you will often hear Javascript referred to as a scripting language — not a programming language. While the difference between scripting and programming languages is becoming much less distinct, it is worth mentioning. Javascript is considered a scripting language because it is processed line-by-line in the browser from top to bottom. This is unlike a true programming language, which is interpreted as machine language or (in the case of Java or .Net languages) as a byte code.


While the distinction referenced above may seem like minutiae, it has important ramifications for the scope and performance of the language itself. The first, and perhaps most obvious ramification of the scripting environment, is that the language is dependent on the browser environment to run. Scripting languages also run more slowly than more traditional programming languages.


Javascript code


Javascript code viewed in a text editor


Despite what you might perceive as drawbacks of using a scripting language, Javascript is becoming an increasingly important tool in the programmer’s toolkit. Due to the growth of mobile applications, and the need to offload heavy processing from a user’s environment on to a server, the service-oriented architecture became important. Javascript is used to facilitate a service-oriented architecture, as it allows direct communication with a web server.


In our example, we’re going to use Javascript to go beyond the HTML5 embedded player and control the media ourselves.


To get started, we’re going to need to load the example that we created in the previous chapter.


1. Open your text editor.


2. Open the file that you created in the first lesson. If you don’t have the file any longer, type the code as it appears below. Remember to save your music file(s) to your drive in the same folder as your HTML code.



<!DOCTYPE html>
<html>
<head>
<title>Audio Player</title>
</head>
<body>
<audio controls="controls">
<source src="music.mp3" type="audio/mpeg">
<source src="music.ogg" type="audio/ogg">
</audio>
</body>
</html>

3. In the <audio> tag, delete the controls="controls" attribute and value. We’re going to be making these controls ourselves using Javascript in this and subsequent lessons.


4. Since the controls will not be visible, we’re going to have to provide some controls to the user. We’ll do this by providing buttons that the user can click. Place your cursor after the closing audio tag and before the closing body tag. You’ll recall that closing tags begin with a forward slash.


5. Add the button code as it appears below:



<button onclick="playMusic()">Play</button><br />
<button onclick="pauseMusic()">Pause</button><br />
<button onclick="stopMusic()">Stop</button><br />

The tag button, as you might guess, creates a visible button on the screen. The text written on the button appears as the content between the opening and closing button tags. The onclick attribute delegates control to a function with the name contained in the value when the button is clicked. When the ‘Play’ button is clicked, control will be delegated to a function called ‘playMusic()’.


I’m sure you’ve also noticed the <br /> tag. This tag creates a line break in the browser display. The forward slash follows that tag name because in this case our <br> tags serve as both opening and closing tags.


Javascript code


The Play, Pause and Stop buttons as they appear in the Firefox browser


6. Next we need to make a space for our Javascript functions. Generally, I put these either in the head of the file or in a separate, attached document. In this tutorial, I’ll be putting the Javascript in the head section of our document. In actual production work, I would attach a separate file; however, for the purposes of this tutorial, it’s simply more convenient to place the functions in the document head. Next, you’re going to put <script> tags after the <title> element in your HTML. After you have done that, your <head> section should appear like this:



<head>
<title>Audio Player</title>
<script>

</script>
</head>

7. Now we’re going to be working inside the <script> element. Inside the script element, the browser knows to interpret the code as Javascript (not HTML). Inside the script tags, create the signature of the playMusic function. The signature is the skeleton of the function. Write code as follows:



<head>
<title>Audio Player</title>
<script>
function playMusic()
{

}
</script>
</head>

The keyword function indicates that we are declaring the function called playMusic. The curly brackets contain the function code itself—often called the implementation. Now we’re going to add three more functions and declare a reference.


8. Modify the head one more time. Modify the code as follows:



<script>
var player;

window.onload = function()
{

}

function playMusic()
{

}

function pauseMusic()
{

}

function stopMusic()
{

}
</script>

Double-check your code to make sure you keyed it in correctly.


There are a couple of new elements in this code block. The line that reads ‘var player’ declares a reference to a variable called player. In the next step we’re going to make that refer to the audio element in the HTML. The ‘window.onload=function()’ declares an anonymous function that will be called when the browser loads. This will allow us to run some initialization code. Finally, we added the necessary function signatures for the pauseMusic and stopMusic functions.


9. Now we’re going to implement the functions. Edit your code in the <script> element so it appears as follows:



<script>
var player;

window.onload = function()
{
player= document.getElementById('player');
}

function playMusic()
{
player.play();
}

function pauseMusic()
{
player.pause();
}

function stopMusic()
{
player.pause();
}
</script>

We’re also going to need to make a change to the <audio> element itself in the HTML. Where it currently reads <audio>, make the following change:



<audio id="player">

We’ve actually done quite a bit of work here. Let’s first turn our attention to the anonymous function that runs after the ‘window.onload’ event. Where the variable player is declared in the first line of the script, the anonymous function assigns the audio element to this variable. Since the audio element now has the id player, we’re able to ‘get’ it with the getElementById(‘player’) function. If you’re coming from another programming language, it may be helpful to think of the Javascript variable player as a pointer to the audio element object.


In the playMusic, pauseMusic and stopMusic functions, we used the player object to start and pause the music. You may be wondering why we didn’t use the stop command inside the stopMusic function. The explanation is simple—there is no stop command. More on this in a moment.


10. This is an excellent time to test your player. If you don’t have any typos or other errors, when you press Play, your music should play. Both the Pause button and the Stop button will stop the player in its current position. Pressing Play again will cause the song to continue. Now we’ll make a small change, which will allow the Stop button to function as expected.


11. Edit your stopMusic function to appear as follows:



function stopMusic()
{
player.pause();
player.currentTime = 0;
}

Test your player again, and you will now notice that the Stop button will cause the song to start over if played again.


The currentTime property allows you to set or read the time elapsed in milliseconds. When we set that to zero, as we do here, we are essentially moving back to the beginning of the audio.


12. Make sure you save and admire your hard work!




Related video course (free)

Author: Mark Lassoff, Learn To Program, Inc.





via Script Tutorials»Script Tutorials | Web Developer Tutorials | HTML5 and CSS3 Tutorials http://www.script-tutorials.com/mp3-player-with-html5-lesson-2/

Comentaris

Entrades populars d'aquest blog

10 alternativas a Cuevana para ver películas online

10 alternativas a Cuevana para ver películas online : Durante este último tiempo, en Cuevana se sucedieron varios “problemas” por los cuales hubo que ajustar algunas cosas antes de tiempo (como el rediseño del sitio), que dejaron a algunos usuarios ciertos problemas para acceder a las películas o series del portal. Pero realmente esto es algo que no incumbe a los usuarios y, como sabemos, existen muchas otras alternativas a Cuevana dando vueltas por Internet, que intentaremos presentar aquí mismo. Los sitios que repasaremos funcionan del mismo modo que Cuevana, mediante la instalación de un plugin que permite visualizar los videos de Megaupload o WUShare, entre otros servicios, en una calidad de imágen realmente excelente. Tal como sucede con el más popular servicio, todos ellos tienen publicidad que en algunos casos resulta insoportable, pero como dice Federico en DotPod “a caballo regalado no se le miran los dientes”. Alternativas a Cuevana 1. Moviezet Posiblemente el mejor clon d...

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

Más de 50 de las mejores herramientas online para profesores

No es una exageración afirmar que hay ciento de aplicaciones educativas por ahí por la red, para todos los gustos y de todos los colores, por lo que es difícil tratar de recogerlas todas en un listado. Sin embargo, algunas destacan más que otras por su innovación y por su capacidad para conseguir adeptos, y esas son las que protagonizan la presente recopilación. Son 50 interesantes herramientas online basadas en las recopilaciones de EduArea , las muchas ya tratadas en Wwwhat’s new y las destacadas por la experiencia. 1. Dropbox : Un disco duro virtual con varios GB gratuitos y al que se accede desde casi cualquier dispositivo. Sin embargo, es muchísimo más que eso, de hecho ya comentamos 20 razones . 2. Google Drive : La evolución de Google Docs que suma a sus múltiples herramientas de creación de documentos, un considerable espacio virtual gratuito. 3. CloudMagic : Una extensión y una app multidispositivo para buscar información simultáneamente en Gmail, Twitter, Facebook, Evernote ...