HTML5 audio API research and learning 1

Source: Internet
Author: User

HTML5 audio API research and learning 1

HTML5 audio

1. audio sprite

The main idea of the audio genie is similar to that of the css genie. It combines an audio into an audio and uses currentTime to obtain the current playback time for differentiation. However, before executing the following code, you need to set audio

Load to the page first. At that time, how can I determine that the page has been loaded with sound? Many of the audio attributes on the mobile end do not support very well. After trying a lot and finding a lot of information on the Internet, now we can use the AudioContext object to manage and play the sound.

        



var audioSprite = document.getElementById("audio1");                    audioData = {                        shake: {                            start: 0,                            length: 10                        },                        win: {                            start: 15,                            length: 15                        }                    }                    document.getElementById("play").addEventListener("click", function () {                        audioSprite.play()                        audioSprite.currentTime = audioData.shake.start;                        //audioSprite.play();                    }, false);                    var handler = function () {                        if (this.currentTime >= audioData.shake.start + audioData.shake.length) {                            this.pause();                            setTimeout(function () {                                audioSprite.removeEventListener("timeupdate", handler, false);                                audioSprite.currentTime = audioData.win.start;                                audioSprite.play();                                audioSprite.addEventListener("timeupdate", handler2, false);                            }, 1000);                        }                    }                    var handler2 = function () {                        if (this.currentTime >= audioData.win.start + audioData.win.length) {                            this.pause();                        }                    }                    audioSprite.addEventListener("timeupdate", handler, false);

2. to generate a sound using AudioContext, you must create one or more sound sources and connect these sound sources through the AudioContext object. These sound sources are not directly connected, however, multiple AudioNodes objects are indirectly connected to various audio signal modules for processing.

An AudioContext object supports multiple audio inputs and audio Image Generation. Therefore, in an audio processing application, you only need to create an AudioContext object.

Var context; if (webkitAudioContext) {context = new webkitAudioContext ();} else {context = new AudioContext (); // standard}
2.1 After creating the AudioContext object, we can use the AudioBuffer object to load audio data. The above button is used to load the sound. Click this button and use the XMLHttpRequest object to obtain the audio data in the MP3 file on the server. Example:

function loadSound() {            var request = new XMLHttpRequest();            request.open("GET", "smbb.mp3", true);            request.responseType = "arraybuffer";            request.onload = function () {                context.decodeAudioData(request.response, function (buffer) {                    console.log(buffer)                }, onError);            }            request.send();        }        function onError(e) {            console.log(e);        }

In the above Code, the user clicks the "load sound" button to execute the loadSound function in the javascript script code. In this function, the XMLHttpRequest object is used to obtain the audio data in the MP3 file on the server, because the audio data is binary data, the responseType attribute value of the XMLHttpRequest object is set to "arraybuffer ". When audio data is not decoded in the MP3 file on the server, you can use the decodeAudioData method of the AudioContext object to decode the audio data.

The decodeAudioData method of the AudioContext object uses three parameters. The first one is an ArrayBuffer object that loads undecoded audio data. The second and second parameters are a function, it indicates the callback function executed when audio data decoding is successful and the callback function executed when audio data decoding fails.

2.2 After the audio is loaded, you can use the createBufferSource object of the AudioBuffer object to create an AudioBufferSourceNode object (representing the sound source of the audio playback device ), specify the buffer attribute value of the AudioBufferSourceNode object as the AudioBuffer object. The Code is as follows:

var source = context.createBufferSource();    source.buffer = buffer;
This buffer is the buffer returned by decodeAudioData in the preceding example.

Next, we need to use the connect Method of the AudioBufferSourceNode object to connect the sound source to the destination attribute value of the AudioContext object (representing the audio playback device ).

source.connect(context.destination);
The connect Method of the AudioBufferSourceNode object uses a parameter. The parameter value is the destination attribute value of the AudioContext object. The attribute value is the audio playback device on the client computer.

Finally, use the start method of the AudioBufferSourceNode object to play the sound.

Source. start (0) // Note: I used to use the noteOn method in many posts on the Internet. At that time, I tested this method undefined. You can use the start () method to play the video. If the start method does not pass the parameter in the IOS system, the method is also undefined. Later, you must give a default parameter.

The entire code at this stage

    
     
     
     
     Audio loading processing is encapsulated into a class.            


<Script> var audioBuffer = null; var context; if (webkitAudioContext) {context = new webkitAudioContext () ;}else {context = new AudioContext ();} // load audio data function loadSound () {var request = new XMLHttpRequest (); request. open ("GET", "smbb.mp3", true); request. responseType = "arraybuffer"; request. onload = function () {context. decodeAudioData (request. response, function (buffer) {/* var audio = new Audio (); audio. src = "smbb.pdf"; audio. play (); */var audioSprite = document. getElementById ("audio1"); audioData = {shake: {start: 0, length: 10}, win: {start: 15, length: 15} document. getElementById ("play "). addEventListener ("click", function () {audioSprite. play () audioSprite. currentTime = audioData. shake. start; // audioSprite. play () ;}, false); var handler = function () {if (this. currentTime> = audioData. shake. start + audioData. shake. length) {this. pause (); setTimeout (function () {audioSprite. removeEventListener ("timeupdate", handler, false); audioSprite. currentTime = audioData. win. start; audioSprite. play (); audioSprite. addEventListener ("timeupdate", handler2, false) ;}, 1000) ;}var handler2 = function () {if (this. currentTime> = audioData. win. start + audioData. win. length) {this. pause () ;}} audioSprite. addEventListener ("timeupdate", handler, false) ;}, onError);} request. send ();} function onError (e) {console. log (e) ;}</script>

To sum up, HTML5 audioAPI is indeed very powerful and interesting to study. However, it takes a lot of time for the technical department to get home, and of course there are also vulnerabilities, please forgive me for saying something wrong. In the next stage, you will have more interesting controls on the playing rhythm, the crossover and mixing of multiple sounds, and the smooth transition between multiple audio files...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.