search
HomeWeb Front-endH5 TutorialHow to embed audio and video in HTML5

How to embed audio and video in HTML5

Jul 17, 2018 pm 02:18 PM
html5

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=&#39;vp8, vorbis&#39;">
    <source src="xx.ogv" type="video/ogg; codecs=&#39;theora, vorbis&#39;">
    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() 方法。

相关推荐:

分享一个简单的HTML5 视频嵌入实例代码

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 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 DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 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 ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The 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 PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools