1, here is a simple example of playing music
(The Controls property tells the browser to have a basic playback control)
Original: HTML5-use <audio> play audio
<audio src= "Hangge.mp3" controls></audio>
2, preload media files
Set preload different property values to tell the browser how to load a media file:
(1) The value is auto: Let the browser automatically download the entire file
(2) The value is none: The browser does not have to download files beforehand
(3) The value is metadata: Let the browser first get the data block at the beginning of the audio file, thus sufficient to determine some basic information (such as the total length of audio)
<!--users click to play before they start downloading-->
<audio src= "Hangge.mp3" Controls preload= "None" ></audio>
3, Auto Play
Use the AutoPlay property to play the browser immediately after it finishes loading the audio file. (If you want to use it as a background music, you can remove the controls attribute)
<audio src= "Hangge.mp3" Controls autoplay></audio>
4, Loop playback
Use the Loop property to play at the beginning of the music playback at the end.
<audio src= "Hangge.mp3" Controls loop></audio>
Sometimes we need to use JS to control the player to achieve music playback, pause. Or use JS to play some sound effects.
1, using JavaScript to control the player on the page
For example, add a <audio> to the page to play the background music (because the controls property is not set, we can not see the playback interface)
<audio id= "Bgmusic" >
<source = src= "Hangge.mp3" type= "Audio/mp3" >
<source = src= "Hangge.ogg" type= "Audio/ogg" >
</audio>
The pause () and Play () methods allow music to pause and resume (combined with the CurrentTime property to stop and replay)
var audio = document.getElementById ("Bgmusic");
Play (Resume playback)
Audio.play ();
Time out
Audio.pause ();
Stop it
Audio.pause ();
Audio.currenttime = 0;
Play again
Audio.currenttime = 0;
Audio.play ();
2, you can also dynamically create <audio> elements
Mode 1
var audio = document.createelement ("audio");
AUDIO.SRC = "Hangge.mp3";
Audio.play ();
Mode 2
var audio = new Audio ("Hangge.mp3");
Audio.play ();
The Canplaytype () method allows you to determine which encoding the browser supports, setting up the corresponding audio file.
if (Audio.canplaytype ("Audio/mp3")) {
AUDIO.SRC = "Hangge.mp3";
}else if (Audio.canplaytype ("Audio/ogg")) {
AUDIO.SRC = "Hangge.ogg";
}