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: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!