top

Using audio Element

This document covers how to play media contents by using audio element.

Overview

Samsung TV supports the audio HTML5 media element. The audio element specifies a standard way to embed audio content in web application. You can use the audio element to play audio files streaming, without a separate plug-in.

To get the most out of audio element, you should first

  • learn to create the audio element

  • learn how to use and control that by using JavaScript

  • learn to apply CSS styles to audio element and modify styles dynamically using JavaScript.

Using JavaScript, the playback can be controlled with Media Events (W3C). The audio element used as media elements inherit all the properties and methods of the HTMLMediaElement interface.

Samsung TV supports the audio formats based upon a standard specs.
For more information, go to Supported Media Formats.

Creating Audio player

The audio element exposes methods, properties, and events to JavaScript. There are methods for playing, pausing, and changing the audio source URL dynamically.

The audio element works in exactly the same way as the video element, with a few small differences as outlined below.

Creating HTML5 Audio Element

Choose one of the two below as you want.

  • HTML

    <body>
    	<audio id='audio'></audio>
    </body>
    
  • JavaScript

    var audioElement = document.createElement('audio');
    document.body.appendChild(audioElement);
    

Adding Attributes and Properties

The HTML representation of a DOM element has attribute. But when represented as a JavaScript object those attributes appear as object property.

To create a audio player, adding necessary attributes and properties to audio element.

  • Attributes for audio element
    The audio element supports a number of attributes to control audio playback and display. This table highlights the basic audio attributes.
    For more information, go to Attributes (MDN)

    Table 1. Basic Audio Attributes
    Attribute Description
    autoplay Specifies that the audio will start playing as soon as it is ready
    controls Specifies that audio controls should be displayed (such as a play/pause button etc)
    loop Specifies that the audio will start over again, every time it is finished
    muted Specifies that the audio output should be muted
    preload Specifies if and how the author thinks the audio should be loaded when the page loads
    src A string that represents a URL that points to a audio file
  • Properties for audio element
    The audio element supports a number of properties to control audio playback and display. This table highlights the basic audio properties.
    For more information, go to Properties (MDN)

    Table 2. Basic Audio Properies
    Property Description
    audioTracks A AudioTrackList that lists the AudioTrack objects contained in the element
    buffered Returns a TimeRanges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed
    currentTime Is a double indicating the current playback time in seconds. Setting this value seeks the media to the new time
    duration Returns a double indicating the length of the media in seconds, or 0 if no media data is available
    ended Returns a Boolean that indicates whether the media element has finished playing
    paused Returns a Boolean that indicates whether the media element is paused
    volume Is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest)

Choose one of these two below as you want.

  • HTML

    <body>
    	<audio id='audio' src='yourAudioURI' loop controls>
    	</audio>
    </body>
    
  • JavaScript

    var audioElement = document.createElement('audio');
    audioElement.src = 'yourAudioURI';
    audioElement.loop = true;
    audioElement.controls = true;
    audioElement.load();
    
    document.body.appendChild(audioElement);
    
Note

  • There is no visual component in audio element — you just need to display controls to play the audio.
  • Other differences from HTML5 video element are as follows:
    a. The audio element doesn’t support the width / height attributes — again, there is no visual component, so there is nothing to assign a width or height to.
    b. It also doesn’t support the poster attribute — again, no visual component.

Attaching Event Listener

Various events are sent when handling audio that are embedded in HTML documents using the audio element.
For more information, go to Media Events(MDN)

var audioElement = document.getElementById('audio');

audioElement.addEventListener('loadeddata', function () {
    console.log('Audio loaded.');
});
audioElement.addEventListener('timeupdate', function () {
    console.log('Current time: ' + audioElement.currentTime);
});
audioElement.addEventListener('seeked', function () {
    console.log('Seek operation completed.');
});
audioElement.addEventListener('stalled', function () {
    console.log('Audio stalled.');
});
audioElement.addEventListener('ended', function () {
    console.log('Audio ended.');
});

Using Method

The methods of audio element are used to control audio player. This table highlights the basic audio methods.
For more information, go to Media Methods(MDN)

Table 3. Basic Audio Methods
Method Description
addTextTrack Adds a text track (such as a track for subtitles) to a media element.
load This method can be useful for releasing resources after any src attribute and source element descendants have been removed.
play Begins playback of the media.
pause Pauses the media playback.
canPlayType Determines whether the specified media type can be played back.
  • play
    The play() method attempts to begin playback of the audio.
var audioElement = document.getElementById('audio');
audioElement.play();
  • pause
    The pause() method will pause playback of the audio, if the audio is already in a paused state this method will have no effect.
var audioElement = document.getElementById('audio');
audioElement.pause();
  • canPlayType
    The canPlayType() method determines whether the specified media type can be played back.
    The return values are :

    • ‘probably’ : The specified media type appears to be playable.
    • ‘maybe’ : Cannot tell if the media type is playable without playing it.
    • ’ (empty string)’ : The specified media type definitely cannot be played.


    For more information, go to canPlayType.

        var audioElement = document.getElementById('audio');
        console.log(audioElement.canPlayType('audio/ogg'));
        console.log(audioElement.canPlayType('audio/mpeg'));
    

Controlling Playback

Seeking Media Time

The currentTime property of audio element sets or returns the current position (in seconds) of the audio playback. When setting this property, the playback will jump to the specified position. Property value is seconds which indicates the position for the playback of the audio, in seconds.

var audioElement = document.getElementById('audio');

/* Move 10 seconds forward */
var seekTime = audioElement.currentTime + 10;
if( seekTime >= 0 && seekTime <= audioElement.duration ){
    audioElement.currentTime = seekTime;
}

/* Move 10 seconds back */
var seekTime = audioElement.currentTime - 10;
if( seekTime >= 0 && seekTime <= audioElement.duration ){
    audioElement.currentTime = seekTime;
}

/* Move timeline to 30 seconds */
audioElement.currentTime = 30;
Important

  • If the metadata of the audio file is loaded, you can move to the assigned timeline position even when the audio file is not playing.
  • For more information, see Retrieving Media Information.

Tricking Play Audio

The playbackRate property of audio element sets or returns the current playback speed of the audio. Property value is playbackspeed which indicates the current playback speed of the audio. For example,

Table 4. Playback Speed of the Audio
Value Description
1.0 It means normal speed.
0.5 It means half speed (slower).
2.0 It means double speed (faster).
-1.0 It means backwards, normal speed.
-0.5 It means backwards, half speed.
var audioElement = document.getElementById('audio');

/* Set to half speed */
var speed = 0.5;
audioElement.playbackRate = speed;

/* Set to double speed */
var speed = 2.0;
audioElement.playbackRate = speed;

Multiple Audios in Media

The src attribute/property contains a path to the audio you want to embed. And this one is available as source element. If there are multiple audios, you can use multiple source element.

  • HTML

    <audio id='audio'>
    	<source class='active' src='yourAudioURI_1'></source>
    	<source src='yourAudioURI_2'></source>
    </audio>
    
    Note

    Each source element also has a type attribute. This is optional, but it is advised that you include them — they contain the MIME types of the audio files, and browsers can read these and immediately skip audios they don’t understand.

  • JavaScript

    var audioElement = document.getElementById('audio');
    
    audioElement.addEventListener('ended', function(e){
    	var activeSource = document.querySelector('#audio source.active');
    	var nextSource = document.querySelector('#audio source.active + source') || document.querySelector('#audio source:first-child');
    
    	// deactivate current source, and activate next one
    	activeSource.className = '';
    	nextSource.className = 'active';
    
    	// update the audio source and play
    	audioElement.src = nextSource.src;
    	audioElement.play();
    })
    

Handling Errors

The error property returns a MediaError object. The MediaError object has a code property containing the error state of the audio.

Table 5. Error State of the Audio
Return Value Description
1 MEDIA_ERR_ABORTED, fetching process aborted by user.
2 MEDIA_ERR_NETWORK, error occurred when downloading.
3 MEDIA_ERR_DECODE, error occurred when decoding.
4 MEDIA_ERR_SRC_NOT_SUPPORTED, audio not supported.
var audioElement = document.getElementById('audio');

audioElement.addEventListener('error', function()
{
  /* Audio playback failed: show a message saying why */
  switch (audioElement.error.code)
  {
     case 1:
        // 'MEDIA_ERR_ABORTED : 1, Media data download is stopped by the user'
        break;
     case 2:
        // 'MEDIA_ERR_NETWORK : 2, Download is stopped due to network error'
        break;
     case 3:
        // 'MEDIA_ERR_DECODE : 3, Media data decoding failure'
        break;
     case 4:
        // 'MEDIA_ERR_SRC_NOT_SUPPORTED : 4, Format not supported'
        break
  }
}, false);