search
HomeWeb Front-endH5 TutorialHTML5 plug-in-free multimedia Media-detailed introduction to audio and video

Audio and video have become more and more popular now
In order to ensure cross-browser compatibility
, various websites still choose to use flash


(Source code intercepted from Youku)

Multimedia tags

Use

HTML5 adds two multimedia tags, audio and video.
The compatibility is pretty good, but lower versions of IE do not support it
Yes It allows us to insert audio and video controls without using any browser plug-ins
and it is very simple


(source code taken from Bilibili) The usage of the

element is as follows:

<audio src="media/xi-Halcyon.mp3" id="demoAudio">不支持H5-audio</audio>
<video src="media/Animation.mp4" id="demoVideo">不支持H5-video</video>

If the content in the tag is not supported by the browser, it will be displayed.
Of course, when using these two elements,
at least add the src attribute , the attribute value is the URL of the resource

But each browser supports different media formats due to copyright issues
So you can use the following method

<audio id="demoAudio">
    <source src="media/xi-Halcyon.mp3">
    <source src="media/xi-Halcyon.ogg">    ...
    不支持H5-audio
</audio>

<video id="demoVideo">
    <source src="media/Animation.mp4">
    <source src="media/Animation.webm">    ...
    不支持H5-video
</video>

to specify different resource formats
Also ensures the compatibility of various browsers

Attributes

In addition to src, the audio and video tags also have some public attributes

AttributeDescription##autoplaycontrolslooppreload


前三个属性属性名与属性值相同,直接添加属性名即可
preload有如下属性值

  • none 不加载数据

  • metedata 仅加载元数据(时长、比特率、帧大小等)

  • auto 浏览器加载它认为适量的媒体内容

比如想要在浏览器添加一段音乐
并且加载后立即播放,循环播放
使用浏览器的播放控件

<audio src="media/xi-Halcyon.mp3" id="demoVideo" autoplay controls loop></audio>

控件的样式各个浏览器都不一样
随着浏览器版本的更新,可能还会更新样式


video元素还有独有的属性poster
属性值是图片资源的url
用来设置视频播放前的一张占位图片

<video src="media/Animation.mp4" id="demoVideo" width="500" height="400" poster="images/preimg.jpg" controls></video>


点击播放后,视频正常播放

脚本化音视频

元素

使用js获取dom节点就很简单了

var a = document.getElementById(&#39;demoAudio&#39;);var v = document.getElementById(&#39;demoVideo&#39;);

类似于image的Image构造函数
Audio也可以通过类似的方式创建(Video不可以)
区别在于Image创建的图片是要插入文档的
但是Audio不需要

var a = new Audio(&#39;song.mp3&#39;);

然后可以为它添加autoplay、loop等属性
然后添加到页面

接口

在获取的DOM节点上可以使用浏览器提供的接口属性和方法
常用的属性、方法如下

  • currentSrc 媒体数据的URL地址

  • volume 播放音量

    • 介于0~1(注意超范围会报错),默认1最大音量

  • muted 是否静音

    • 设置true进入静音模式

  • playbackRate 媒体播放速度

    • 默认1.0常速,>1快进,

  • defaultPlaybackRate 媒体默认的播放速度

  • currentTime 当前播放时间(单位s)

  • duration 媒体时长(单位s)

  • play() 播放音/视频

  • pause() 暂停音/视频

  • load() 重新加载音/视频(通常用于修改元素属性后)


除此之外还有

  • played 已经播放的时间段

  • buffered 已经缓冲的时间段

  • seekable 用户可以跳转的时间段

它们都是TimeRanges对象
每个对象都有一个length属性(表示当前时间段)
以及start()和end()方法(返回当前时间段的起始时间点和结束时间点,单位s)
start()和end()都有一个数字参数,表示第一个时间段
确定当前缓存内容百分比:

var percentLoaded = Math.floor(song.buffered.end(0)/song.duration*100)

下面三个布尔属性表示媒体播放器的状态

  • paused 是否暂停

  • seeking 是否正调到一个新的播放点

  • ended 是否播放结束并停止


并不是所有浏览器都支持video和audio的所有编解码器
canPlayType()方法就是用来鉴定时候支持某一格式的媒体资源
返回字符串maybe、probably或空字符串
如果只传入MIME类型,则返回maybe
如果同时传入MIME类型和编解码器,则返回probably(可能性增加了)
只是因为媒体文件只不过是音/视频的容器
真正决定文件能否播放的还得是编码格式

console.log(a.canPlayType(&#39;audio/mp4&#39;)); 
//maybeconsole.log(a.canPlayType(&#39;audio/mp4;codecs="mp4a.40.2"&#39;)); 
//probably

下面的状态位属性也了解一下

  • readyState 就绪状态

    • 0 = HAVE_NOTHING - 没有关于音/视频是否就绪的信息

    • 1 = HAVE_METADATA - 关于音频/视频就绪的元数据

    • 2 = HAVE_CURRENT_DATA - 关于当前播放位置的数据是可用的,但没有足够的数据来播放下一帧/ms

    • 3 = HAVE_FUTURE_DATA - 当前及至少下一帧的数据可用

    • 4 = HAVE_ENOUGH_DATA - 可用数据足以开始播放

  • netWorkState 网络状态

    • 0 = NETWORK_EMPTY - 音/视频尚未初始化

    • 1 = NETWORK_IDLE - 音/视频是活动的且已选取资源,但并未使用网络

    • 2 = NETWORK_LOADING - 浏览器正在下载数据

    • 3 = NETWORK_NO_SOURCE - 未找到音/视频来源

  • error.code 错误状态

    • 1 = MEDIA_ERR_ABORTED - 取回过程被用户中止

    • 2 = MEDIA_ERR_NETWORK - 当下载时发生错误

    • 3 = MEDIA_ERR_DECODE - 当解码时发生错误

    • 4 = MEDIA_ERR_SRC_NOT_SUPPORTED - 不支持音频/视频

事件

除了接口属性方法以外
还有必不可少的事件模型
如果我们不想使用浏览器的控件而是定义自己的播放控制组件
就要使用这套事件了

  • play 播放时触发

  • pause 暂停时触发

  • loadedmetadata 浏览器获取完媒体元数据时触发

  • loadeddata 浏览器加载完当前帧媒体数据时触发

  • ended 播放结束后停止时触发

初次之外还有很多事件
很多不常用
在w3c截了一张图


通过接口与事件
也可以简单的实现自己简陋的音乐播放器

<button id="btn">播放</button><span id="cur">0s</span>/<span id="dur">0s</span><br>音量:<input type="range" id="vol">
var audio = new Audio(&#39;media/xi-Halcyon.mp3&#39;);
var btn = document.getElementById(&#39;btn&#39;);
var vol = document.getElementById(&#39;vol&#39;);
var cur = document.getElementById(&#39;cur&#39;);
var dur = document.getElementById(&#39;dur&#39;);var state = &#39;pause&#39;;

vol.value = 100;
audio.onloadeddata = function(){
  dur.textContent = Math.floor(audio.duration) + &#39;s&#39;;
}

setInterval(function(){
  cur.textContent = Math.floor(audio.currentTime) + &#39;s&#39;;
}, 200);

btn.onclick = function(){
  if(state === &#39;play&#39;){
    state = &#39;pause&#39;;
    btn.textContent = &#39;播放&#39;;
    audio.pause();
  }else{
    state = &#39;play&#39;;
    btn.textContent = &#39;暂停&#39;;
    audio.play();
  }
}


vol.oninput = function(){
  audio.volume = vol.value/100;
}

After setting this attribute, the audio/video resource is ready Play immediately
After setting this property, the browser playback control controls will be displayed
After setting this attribute, the audio/video will loop and start playing again after it ends
After setting this attribute, the audio/video will be played when the page is loaded Load and prepare to play (using autoplay will ignore this attribute)

The above is the detailed content of HTML5 plug-in-free multimedia Media-detailed introduction to audio and video. 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
H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web 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 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.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.