HTML5 uses the audio and video elements to embed audio and video content. It allows browsers that support HTML5 to play video and audio without installing any plug-ins.
In addition, JavaScript APIs related to these two tags are provided, so that we can create our own audio and video controls:
<!-- 嵌入视频 -->
<video id="player"
src="xxx.ogg"
poster="mymovie.jpg"
width="300" height="200">
Video player not available.
</video>
<!-- 嵌入音频 -->
<audio src="xxx.mp3" id="myAudio">Audio player not available.</audio>Both of these two tags must include src attribute, which is the address of the media file to be loaded. The width and height attributes specify the size of the video player. The poster attribute is an image that will be displayed while the video is loading. Content between the opening and closing tags is fallback content, meaning it is displayed if the browser does not support these two tags. Because not all browsers support all media formats, different media sources can be specified. The `` tag will be used at this time:
<!-- 嵌入视频 -->
<video id="player">
<source src="xx.webm" type="video/webm; codecs='vp8, vorbis'">
<source src="xx.ogv" type="video/ogg; codecs='theora, vorbis'">
Video player not available.
</video>
<!-- 嵌入音频 -->
<audio id="myAudio">
<source src="xx.ogg" type="audio/ogg">
<source src="xx.mp3" type="audio/mpeg">
Audio player not available.</audio>The browsers that support these two tags are: IE9, Firefox 3.5, Safari 4, Opera 10.5, Chrome, iOS version of Safari and Android version of Webkit.
1 Attributes
The audio and video elements have these common attributes:
| Attributes | type of data | illustrate |
|---|---|---|
| autoplay | Boolean value | Get or set the autoplay flag. |
| buffered | time limit | Downloaded buffered time range object. |
| bufferedBytes | Byte range | Downloaded buffered byte range object. |
| bufferingRate | Integer | Download rate, average number of bits received per second. |
| bufferingThrottled | Boolean value | Whether to throttle the buffer. |
| controls | Boolean value | Get or set the controls attribute to control the display and hiding of the browser's built-in controls. |
| currentLoop | Integer | The number of times the media file has been cycled. |
| currentSrc | String | The URL of the currently playing media file. |
| currentTime | Floating point number | The number of seconds that has been played. |
| defaultPlaybackRate | Floating point number | Get or set the playback speed, the default is 1 second. |
| duration | Floating point number | Total playback time, unit is seconds. |
| ended | Boolean value | Whether the playback has ended. |
| loop | Boolean value | Get or set [whether to start playing from the beginning after the playback is completed]. |
| muted | Boolean value | Get or set [whether to mirror the sound]. |
| networkState | Integer | Network connection status; 0: empty; 1: loading; 2: loading original data; 3: the first frame has been loaded; 4: loading completed. |
| paused | Boolean value | Whether to pause. |
| playbackRate | Floating point number | Get or set [current playback speed]. |
| played | time limit | The current playing time. |
| readyState | Integer | Is it ready? 1: Data is not available; 1: The current frame can be displayed; 2: Playback can be started; 3: Playback can be done from beginning to end. |
| seekable | time limit | The time range that can be searched. |
| seeking | Boolean value | Whether the player is moving to the new location of the media file. |
| src | String | Source of media files, this source can be overridden at any time. |
| start | Floating point number | Get or set the [start playback position], the unit is seconds. |
| totalBytes | Integer | The total number of bytes required by the current resource. |
| videoHeight | Integer | The height of the video, only applicable to video. |
| videoWidth | Integer | The width of the video, only applicable to video. |
| volume | Floating point number | Get or set [Current Volume] from 0.0 to 1.0. |
2 事件
audio 和 video 元素有这些共有的事件:
| 事件 | 说明 |
|---|---|
| abort | 下载中断。 |
| canplay | 可以播放;readyState 为 2。 |
| canplaythrough | 播放可以继续,即不会被中断;readyState 为 3。 |
| canshowcurrentframe | 当前帧已下载;readyState 为 1。 |
| dataunavailable | 没有数据导致不能播放;readyState 为 0。 |
| durationchange | 改变了 duration 的值。 |
| emptied | 网络连接关闭。 |
| empty | 发生错误导致下载停止。 |
| ended | 已播放到末尾,所以播放停止。 |
| error | 下载期发生网络错误。 |
| load | 已加载完成。可能会被废弃,建议使用 canplaythrough。 |
| loadeddata | 媒体的第一帧已加载。 |
| loadedmetadata | 媒体的元数据已加载。 |
| loadstart | 下载已开始。 |
| pause | 播放已被暂停。 |
| play | 媒体已接受到开始播放的指令。 |
| playing | 媒体已开始播放。 |
| progress | 正在下载。 |
| ratechange | 改变了播放速度。 |
| seeked | 搜索结束。 |
| stalled | 浏览器正尝试下载,但未接收到数据。 |
| timeupdate | currentTime 被非法更新。 |
| volumechange | 改变了 volume 或 muted 值。 |
| waiting | 播放暂停,等待下载更多的数据。 |
之所以定义了这么多的事件,就是为了开发人员能够只使用少量的 HTML 和 JavaScript 就可以编写出自定义的音、视频播放器!
3 自定义媒体播放器
<p class="mediaplayer">
<p class="video">
<video id="player"
src="http://people.mozilla.com/~prouget/demos/resources/videos/billyBrowsers.ogg"
poster="mymovie.jpg"
width="300" height="200">
Video player not available.
</video>
</p>
<p class="controls">
<input type="button" value="Play" id="video-btn">
<span id="curtime">0</span><span id="duration">0</span>
</p>
</p>现在我们加一些 JavaScript ,就可以自定义一个简单的视频播放器:
//取得元素引用
var player = document.getElementById("player"),
btn = document.getElementById("video-btn"),
curtime = document.getElementById("curtime"),
duration = document.getElementById("duration");//实测,得不到整个视频的总体播放时间
//更新播放时间
duration.innerHTML = player.duration;
//为按钮添加事件处理程序
EventUtil.addHandler(btn, "click", function (event) {
if (player.paused) {
player.play();
btn.value = "Pause";
} else {
player.pause();
btn.value = "Play";
}
});
//定时更新当前时间
setInterval(function () {
curtime.innerHTML = player.currentTime;
}, 250);可以进一步扩展这个视频播放器,让它可以使用更多的属性,监听更多的事件。同样的代码也可以用于 audio 元素。
4 检测编解码器的支持情况
audio 和 video 元素都有一个 canPlayType() 方法,它接收一个格式/编解码器的字符串,返回 “probably”、”maybe”、”“,所以这样这样使用:
if (audio.canPlayType("audio/mpeg")){
...
}因为真正决定文件是否能够播放的是编码格式,所以建议同时传入 MIME 类型和编解码器,这样检测会更准确:
if (audio.canPlayType("audio/ogg; codecs=\"vorbis\"")){
...
}注意,编解码器必须使用引号!下面列出已得到支持的音/视频格式和编解码器:
| 音频 | 字符串 | 支持的浏览器 |
|---|---|---|
| AAC | audio/mp4; codecs=”mp4a.40.2” | IE9+、Safari4+、iOS 版的 Safari |
| MP3 | audio/mpeg | IE9+、Chrome |
| Vorbis | audio/ogg; codecs=”vorbis” | Firefox 3.5+、Chrome、Opera 10.5+ |
| WAV | audio/wav; codecs=”1” | Firefox 3.5+、Chrome、Opera 10.5+ |
| 视频 | 字符串 | 支持的浏览器 |
|---|---|---|
| H.264 | video/mp4; codecs=”avcl.42E01E, mp4a.40.2” | IE9+、Safari4+、iOS 版的 Safari、Android 版 WebKit |
| Theora | video/ogg; codecs=”theora” | Firefox 3.5+、Chrome、Opera 10.5+ |
| WebM | video/webm; codecs=”vp8, vorbis” | Firefox 4+、Chrome、Opera 10.6+ |
5 Audio 类型
audio 元素有一个原始的 JavaScript 构造函数 Audio,可以利用它来控制什么时候播放音频:
var audio = new Audio("xxx.mp3");
EventUtils.addHandler(audio, "canplaythrough", function(event){
audio.play();
});上面的代码实现了这样的功能:当下载完成后自动播放音频。
在 iOS 中,调用 play() 会弹出一个对话框,得到用户许可后才可以播放。
如果想要在一个音频播放完之后在播放另一个音频,可以在 onfinish 事件中调用 play() 方法。
相关推荐:
The above is the detailed content of How to embed audio and video in HTML5. For more information, please follow other related articles on the PHP Chinese website!
Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AMHTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.
H5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AMBest practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.
H5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AMWeb standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.
Is H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AMH5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.
H5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AMH5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.
What Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AMH5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo
H5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AMThe tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.
The Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AMHTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment







