Audio is used to embed audio elements in a document.

The audio element is a new inline tag in HTML5 that is not supported in IE8 and below.

If the browser does not support the video element or cannot play the audio, the alternative text (the content between the start and end tags) is displayed.

<audio src="music.mp3"> Current browser does not support audio tag </audio>Copy the code

Tag attributes

  • autoplay: Audio will automatically play as soon as possible without waiting for the entire audio download to complete
  • controls: The browser provides control panels for sound, playback progress, and pause. Users can control audio playback
  • loop: Plays the audio loop
  • muted: Mute or not. The default value isfalse, indicates that there is a sound
  • preload: Preloading, includingauto,metadataandnoneThree parameter values,autoMeans to load audio,metadataMeans that no audio is loaded, but audio metadata (such as audio length) is required,noneIndicates that no audio is loaded. If specified as an empty string, is equivalent toauto. Pay attention toautoplayAttribute priority is higher thanpreloadIf,autoplayWhen specified, this property is ignored and the browser loads the audio for playback
  • src: Embedded audioURL

Set up multiple audio resources

Different browsers support different audio playback formats. Generally, multiple audio formats are placed for compatibility, and the browser selects the appropriate audio format from top to bottom.

<audio controls> <source src="music.ogg" type="audio/ogg"> <source src="music.mp3" type="audio/mpeg"> <source SRC ="music.wav" type="audio/ wav" > Current browser does not support audio tag </audio>Copy the code

Element attributes

read-only

  • duration: Dual-progress floating point number, the duration of audio playback, in seconds. Returns if the audio is not available or not loadedNaN
  • paused: Returns if audio is paused or does not start playingtrue
  • ended: Indicates whether the audio playback endstrue
  • error: In case of an errorMediaErrorobject
  • currentSrc: Returns the audio being played or loadedURLAddress corresponding to the browser insourceElement to select a file
  • seeking: Whether the user moves or jumps to a new point in the audio
<audio preload="auto" src="music.mp3" onseeking="fn()" controls />
<script>
    var audio = document.querySelector('audio')
    function fn() {
        console.log(audio.seeking)
    }
</script>
Copy the code

Read/write

  • autoplay: Sets the audio automatically playing or queries whether the audio is setautoplay
  • loop: Sets or queries whether audio is played in a loop
  • currentTime: Returns the current playback time of the audio, a double-precision floating point number in seconds. If the audio is not played, you can set the time when the audio starts to play. During audio playback, you can set the audio playback time
  • controls: Displays or hides the audio control panel, or queries whether the audio control panel is visible
  • volume: Returns the volume value between0-1Or set the volume value
  • muted: Sets or queries whether to mute
  • playbackRate: Sets or queries the playback speed of audio.1The normal velocity is greater than1Fast forward,0-1Between means slow forward,0 The control panel is still playing, just at a speed of0)

Special attributes

played

Represents the range of audio that the user has played, and returns the TimeRanges object, which contains a length attribute and two methods, start() and end().

  • length: Gets the number of audio ranges that have not started playing as0, at least after it starts playing1
  • start(index): Gets the start of an audio range
  • end(index): Gets the end position of an audio range

If the user moves or jumps a point in the audio, multiple audio ranges are available.

The following is an audio clip in which the user jumped the player twice, so played. Length is 3, and the three audio ranges are respectively the start of the play, the first jump point, and the second jump point.

Some of the above code is as follows.

<audio src="music.mp3" controls></audio>
<button id="btn">console.log</button>

<script>
    var btn = document.querySelector('#btn')
    var audio = document.querySelector('audio')

    btn.addEventListener('click'.() = > {
        const length = audio.played.length
        console.log(`length: ${length}`)

        for (var i = 0; i < length; i++) {
            var start = audio.played.start(i)
            var end = audio.played.end(i)

            console.log(`index: ${i}, start: ${start}, end: ${end}, durations: ${end - start}s`)}})</script>
Copy the code

buffered

Buffered. Length is 1, buffered. Start (0) is 0, buffered. End (0) is the length of the audio.

seekable

The TimeRanges object is returned. If the audio is fully loaded, seekable. Length is 1, seekable. Seakable. Length = 0; start(0) and end(0) do not exist.

networkState

Get audio network range for detailed reference.

  • 0:NETWORK_EMPTYThe audio has not been initialized
  • 1:NETWORK_IDLE, the browser has selected the encoding format to play the media, but has not yet established a network connection
  • 2:NETWORK_LOADINGThe browser is loading
  • 3:NETWORK_NO_SOURCEAudio resource not found

error

When audio is normally loaded, null is returned, and if an error occurs during loading, the browser returns a MediaError object. The MediaError object contains code and message properties. Message is the error description information and code is the following error code.

  • 1:MEDIA_ERR_ABORTEDThe audio loading process was terminated due to user action
  • 2:MEDIA_ERR_NETWORKVerify that the audio resource is available, but a network error occurred while loading and the audio load was aborted
  • 3:MEDIA_ERR_DECODEConfirm that the audio resource is available, but decoding error occurred
  • 4:MEDIA_ERR_SRC_NOT_SUPPORTEDThe audio format is not supported or the resource is not available

methods

play

When the audio is played, return ‘Resolved’ when it is played successfully and ‘Rejected’ when it fails for any reason.

var audio = document.querySelector('audio')
audio.play()
    .then(() = > { })
    .catch(() = >{})Copy the code

pause

Pause audio, no return value, detailed reference.

var audio = document.querySelector('audio')
audio.pause()
Copy the code

load

Reload the resource specified by SRC, refer to it for details.

var audio = document.querySelector('audio')
audio.src = 'music.mp3'
audio.load()
Copy the code

The event

Common event

  • Loadstart: triggered when audio starts to load
  • durationchange:durationTriggered when the property is updated
  • Loadedmetadata: Triggered when audio metadata is loaded
  • Loadeddata: Triggered when the first frame of the audio has been loaded before the entire audio has been loaded
  • Progress: Triggered while audio is loading
  • Canplay: Triggered when the browser can start playing audio
  • Canplaythrough: triggered when the browser expects to be able to continue playing the specified audio without stopping to buffer

Other events

  • Abort: Triggered when audio terminations are not caused by errors
  • emptied: The audio is loaded and then emptied, such as load is called to reload
  • ended: The playback is completeloopProperty that does not trigger after audio playback ends
  • Error: An error occurs
  • Play: Indicates the play event. The event is triggered after the first play or pause
  • Playing: A playing event that is triggered when it is played for the first time, played after pausing, or looped after playing
  • Pause: A pause event
  • Ratechange: The playback rate changes
  • Seeking: The playpoint changes
  • Seeked: The playpoint changes over
  • Cost: triggered when browser attempts to obtain audio but audio is not available
  • Suspend: Trigger when audio loading is paused
  • timeupdateAudio:currentTime Change trigger
  • Volumechange: Triggered when volume changes, including mute
  • Waiting: triggered when buffering the next frame before playing