Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the audio tag and video tag of HTML5

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the HTML5 audio tag and video tag how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe that you will have a harvest after reading this HTML5 audio tag and video tag how to use the article, let's take a look.

The introduction of audio and video tags can be said to fill the gap in HTML audio and video playback tags. For a long time, HTML does not have its own playback label, but uniformly uses such a tag to play.

Audio tag

Audio tags support audio in HTML pages, and we are free to embed music and audio streams in HTML pages. Audio tags are described in detail below.

1. Check whether the browser supports audio tags

In any case, we recommend that readers test the browser's capabilities when using the new generation of HTML5 tags, such as the following code:

Your browser currently does not support HTML5's audio tag.

If this browser displays the words "your browser does not currently support HTML5's audio tag", this browser does not support HTML5's audio tag, otherwise it does.

This detection method is suitable for many new closed tags and does not need to be judged by JavaScript scripts.

2. Related attributes of audio tags

The attributes of audio tags are similar to those of embed tags in HTML4 era, and they are relatively easy to apply.

The relevant attributes of the audio tag are listed below:

Format description of attribute name value

Src xs:anyURI specifies the URL address of the audio source file

Autoplay autoplay plays automatically when the page is loaded

Loop loop automatically loops the files specified under this tag

Controls controls users can control the audio.

Preload preload this is a preload processing property, and whenever the tag is processed, the relevant data will be loaded automatically. However, if you use "autoplay", the attribute is ignored

3. Browser compatibility of audio tags

Since audio and video standards have not yet been unified on browsers, and each manufacturer has its own position and attitude, and may not be completely unified for a long time, we suggest that readers adopt compatibility. This can effectively cover most browsers that support audio and video tags.

4. Common problems with using audio tags

For audio tags, we summarize your common questions as follows.

Can audio tags be dragged and played like a Flash player?

The audio tag can be played with a jump. As long as it is located directly to the target position, the playback method can be executed.

The code is roughly as follows:

Var audio = document.getElementById ('audio'); / / get the audio tag object

Audio.currentPosition; / / get the position to be played

Audio.play ()

Does the audio tag have volume control?

The audio tag can directly control the volume during playback, which is used by audio.volume.

Can audio tags get information about audio files?

Audio tags cannot read audio content information.

Can audio tags be pre-read or preloaded?

The audio tag can be preloaded and easy to use. You only need to add the preload attribute to the tag:

Your browser does not support audio tags

Can audio tags make sound?

Audio tags cannot be directly manipulated to create new audio content information.

Video tag

HTML5 directly supports video playback through video tags, so that the majority of browsers finally get rid of the shackles of Flash. In Linux and Mac OS, support for Flash is poor. In the environment of non-Windows operating system, Flash consumes a lot of CPU. This is a painful experience for many non-Windows users, although the situation has improved recently.

In addition, although mobile devices have been widely used and popularized, there is no Flash technology that can be fully supported (except that Symbian can support simple Flash). YouTube, the world's largest video website, took the lead in launching the HTML5 version, and many websites have developed versions without Flash to cater to mobile devices.

1. Check whether the browser supports video

Like audio tags, when we use the new generation of HTML5 tags, we should use standard browser capability testing methods to test browser capabilities, such as the following code:

Your browser currently does not support HTML5's video tag.

If this browser displays the words "your browser does not currently support HTML5's video tag", this browser does not support HTML5's video tag, otherwise it does.

2. Browser compatibility of video tags

Compatibility issues that people are usually concerned about can actually be achieved in a very simple way. Here is a sample code for "elegant downgrade" for readers to think about and use for reference:

Your browser does not support anything but download

3. Introduction to the related attributes of video

Format description of attribute name value

Src xs:anyURI specifies the URL address of the video source file

Autobuffer autobuffer allows automatic buffering

Autoplay autoplay allows auto playback

Loop loop allows automatic loop playback

Controls controls allows users to control video

Width cm | em | en | in | px | pt |% display width of video image. When the height is not specified, its value will be proportional to the video width.

Height cm | em | en | in | px | pt |% display height of the video image. When the width is not specified, its value will be proportional to the video height.

Poster xs:anyURI this attribute value is linked to an image when the video does not respond or is not buffered enough. The image will be displayed in a certain proportion.

Source tag format this is a child tag that comes with video and is specifically used to describe the src attribute and the type attribute of the source file

4. Video formats supported by video

At present, the video formats supported by video are still changing. After testing most browsers, we summarize the following three formats that can meet the actual needs of the project.

 Ogg . Ogg file with Theora video encoding and Vorbis audio encoding.

 MPEG4 . MPEG-4 file with H.264 video encoding and AAC audio encoding.

 WebM . WebM file with VP8 video encoding and Vorbis audio encoding.

5. General interface standard

Both video and audio tags use the same DOM interface based on abstract HTMLMediaElement.

The standard IDL specification interface is introduced below to facilitate readers to learn to control a variety of video and audio streams.

Events:

Loadstart loading start

Browsers start looking for media data as part of the resource selection algorithm

Prerequisite for use: network status is loaded (NETWORK_LOADING)

Progress Progress

Browsers get media data

Prerequisite for use: network status is loaded (NETWORK_LOADING)

Suspend hangs

Browsers intentionally do not get media data currently, but they do not download all media resources.

Prerequisite for use: network status is idle (NETWORK_IDLE)

Abort termination

The browser stops obtaining the media data until the media data is fully downloaded. This cannot be attributed to a mistake.

Use prerequisites: an error is an object that represents the MEDIA_ERR_ABORTED code for media error termination. At this point, whether the network is idle or idle depends on when the download is terminated.

Error error

An error occurs when getting the data

Use prerequisites: an error is an object that represents the MEDIA_ERR_NETWORK code or higher-level code that the media error terminates. At this point, whether the network is idle or idle depends on when the download is terminated.

Emptied idle

Media elements whose previous network state is not empty have just shifted to this state (either because a fatal error was reported during download, or because the load () method is called when the resource selection algorithm is already running, in which case the emptied event occurs at the same time as the call to the load () method)

Prerequisites for use: the network state is empty, and all IDL attributes are initialized

Stalled delay

The browser is getting the data, but the data is a little unexpected and doesn't come.

Prerequisites for use: network status is mounted (NETWORK_LOADING)

Play playback

The replay has begun. When the play () method returns, continue to play

Use prerequisites: the most recent pause is false

Pause pause

Replay has been stopped. When the pause () method returns, continue to play

Use prerequisites: the most recent pause is true

Loadedmetadata loads media data

Browsers determine the duration and scale of media resources

Prerequisites for use: the state of preparation is recently in the state of having all the current data or loading more than the required data for the first time

Loadeddata load data

The data that the browser can return is located at the location of the current replay for the first time.

Prerequisites for use: the preparation status has recently been promoted to the state of possessed data or for the first time greater than the required data.

Waiting wait

The replay is stopped because the next frame is not available, but the browser hopes to get the architecture in the process.

Prerequisites for use: the most recent preparation status is equal to or less than the current data, and the pause is false. Its status is either the search is true, or the current playback position is not included in the buffered data.

Playing is playing

Playback is started

The preparation status is recently equal to or more than the future data, the pause is false, the search is also false, or the current playback position is included in the buffered data.

Canplay can play

Browsers can continue to play back media data, but if the playback operation starts now, there is no need to stop and wait for further buffering, and media resources cannot work until the end at the current playback rate.

Prerequisites for use: the readiness status has recently been increased to future data or more

Canplaythrough can be played from beginning to end.

If the browser starts playback now, the media resource can keep working at the current playback rate without having to stop and wait for further buffering

Prerequisites for use: preparation status is recently equal to sufficient data

Seeking is looking for

The property of finding IDL was changed to true, and the search operation took a long time.

Seeked search

The property that looks for IDL is changed to false

Timeupdate time update

As part of normal playback, the current playback position is changed, or playback is performed in an interesting way, such as intermittently

End of ended

Playback is stopped because it has reached the end of the media resource

Prerequisites for use: the current time is equal to the time when the media resource ends; the end is true

Ratechange exchange rate

The defaultPlaybackRate or playbackRate property has been updated

Exchange of durationchange duration

The duration property has been updated

Volumechange volume swapping

The volume property or the muted property has been modified. Start working after the installation of the relevant properties has been returned

6. Problems in video

The multimedia application prospect of Web is very broad, but HTML5 also has its own problems: so far, the video format standard on web pages has not been unified. Apple and Microsoft support H.264 standard (MPEG4). Google, Mozilla and Opera support Ogg Theora (Ogg) and WebM.

The debate over video format standards has not been a matter of a day or two, and these arguments and their consequences have greatly affected the use of video tags by major platforms and developers. However, the platform with video tags is bound to face the problem of whether to use H.264 or Ogg. If both are used, it is necessary to use two formats for the same resource file, which brings a lot of repetitive format conversion work, which is probably a headache for many people.

7. Audio Data API

Browser manufacturers have great hopes for the extension of Audio API, and Mozilla is even more advanced in its research on Audio. In their view, browsers can not only play sound, but should also be able to make sound.

Audio Data API is a media element and supplement to the HTML5 specification that allows developers to store and read external data for sound effects (also known as post-set data) as well as native data for the audio itself. Developers can visualize these sound data, analyze them, and even create new sound data. This is a great exploration and expansion in the audio field of browsers.

Events under Moz

 loadedMetadata event. This event is triggered when data from a media is transmitted to the user's computer. It has three properties, as shown below.

MozChannels . The number of channels.

MozSampleRate . Sampling frequency (times per second).

MozFrameBufferLength . The total number of samples of all channels per event.

The data under these attributes will be used when decoding the audio data stream.

 mozAudioAvailable event. When an audio source is played, the audio data is transferred to the audio processing level and the content is entered into the audio buffer (depending on the size of the mozFrameBufferLength). When the buffer is filled, a mozAudioAvailable event is triggered. The playback, pause and jump of audio will affect the audio data streaming. The event has two properties, as shown below.

FrameBuffer . A frame buffer (an array) containing decoded audio data (floating-point numbers). (note: content is not separated by the corresponding channels, but mixed together, such as a two-channel signal: Channel 1-content 1, channel 2-content 1, channel 1-content 2, channel 2-content 2, channel 3-content 1, channel 3-content 2. )

Time . Timestamp, calculated from the start time (unit of measurement: seconds).

The following code is the source code used to describe the above two events:

Hello

Function loadedMetadata () {

Channels = number of audio.mozChannels; / / channels

Rate = audio.mozSampleRate; / / sampling frequency (times per second)

FrameBufferLength = audio.mozFrameBufferLength; / / Total number of samples

}

Function audioAvailable (event) {

Var frameBuffer = event.frameBuffer

Var t = event.time

Var text = "current location:" + t + "\ n"

Text + = frameBuffer [0] + "" + frameBuffer [1]

Raw [XSS _ clean] = text

}

Var raw = document.getElementById ('raw')

Var audio = document.getElementById ('myaudio')

Audio.addEventListener ('mozAudioAvailable',audioAvailable, false); / / listen for events

Audio.addEventListener ('loadedMetadata',loadedMetadata, false); / / listen for events

Manufacturing audio stream

According to this API, we can use the JavaScript script to format the audio stream and then write the audio data. The developer only needs to create an audio object and then use the mozSetup () method to set the number and frequency of channels (Hz).

Take a look at the source code below:

Var testA = new Audio (); / / instantiate an audio object

TestA.mozSetup (2Jing 44100); / / set the format of this object to "dual channel, 44.1kHz"

Var ADU = [0.242, 0.127, 0.014]; / / use JavaScript array to store sound data (of course)

/ / you can also use other methods that you are familiar with to store sound

/ / data)

Var audio_Stream = testA.mozWriteAudio (ADU); / / write the audio stream with the mozWriteAudio () method

Note that not all samples are written to the stream. The function returns the number of samples written to the stream, which is good for the next time the data is written.

Modify audio stream

Because both the mozAudioAvailable event and the mozWriteAudio () method use Float32Array to pass values, it is possible to connect the output of one audio stream directly to (or after processing) another audio stream. The solution is simple, just modify the contents of the array. At the same time, you can also block, synthesize, divide the track volume and merge the audio at any time.

8. Web Audio API

This API is provided by Google, and the best test environment is Chrome 11 and above.

Web Audio API has many interfaces: sources, parameters, buffers, process events, listeners, amplifiers, delay effects, spatial effects, convolution effects, real-time analysis, dynamic comparators, filters and channel splitters. Here is a brief introduction according to the translation document of the W3C working group.

 amplifier (AudioGainNode). The main purpose is to amplify the audio effect, which has two parameters, numberOfInputs and numberOfOutputs, and only one Gain (gain) attribute.

 delay effect (AudioDelayNode). It mainly amplifies the audio effect, which has two parameters, numberOfInputs and numberOfOutputs, and only one delayTime (delay time) property.

 space effect (AudioPannerNode). It is mainly the calculation of audio dissipation in dimensional space, including the calculation of sound direction, Doppler effect and so on.

 convolution effect (AudioConvolverNode). Mainly used to simulate the sound effects of the environment.

 real-time analysis (AudioRealtimeAnalyserNode). It is mainly used for fast Fourier transform to visualize video. It has five attributes, which are fftSize, frequencyBinCount, minDecibels, max-Decibels, and smoothingTimeConstant.

This is the end of the article on "how to use the audio tag and video tag of HTML5". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use HTML5 audio tags and video tags". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report