[HTML]audio音频标签的属性和事件

/ 31,821评论 / 109361阅读 / 2点赞

<audio>是HTML5新加入的用于播放音频的标签,HTML5已经得到广泛的支持,所以我们可以放心使用这个标签;利用它,可以轻松地在网页上播放音频,制作音乐播放器等。下面我们来聊聊它的属性和事件

概念

元数据


属性

兼容性提示

<audio>
  能看到这段话,说明您的浏览器不支持 audio 标签捏
</audio>

controls默认音乐控制面板

<audio controls>
  能看到这段话,说明您的浏览器不支持 audio 标签捏
</audio>
<audio controls="controls">
  能看到这段话,说明您的浏览器不支持 audio 标签捏
</audio>

src音频文件链接

<audio src="./song.mp3" controls>
  能看到这段话,说明您的浏览器不支持 audio 标签捏
</audio>

source资源文件标签


<audio controls>
    <source src="./song.ogg" type="audio/ogg">
    <source src="./song.mp3" type="audio/mpeg">
    能看到这段话,说明您的浏览器不支持 audio 标签捏
</audio>

autoplay自动播放

<audio autoplay>
  您的浏览器不支持 audio 标签捏
</audio>
<audio autoplay="autoplay">
  您的浏览器不支持 audio 标签捏
</audio>

loop开启循环

<audio loop src="./song.mp3">
  您的浏览器不支持 audio 标签捏
</audio>

muted静音

<audio muted src="./song.mp3">
  您的浏览器不支持 audio 标签捏
</audio>

preload预加载方式

<audio preload="auto" src="./song.mp3">
  您的浏览器不支持 audio 标签捏
</audio>

JS操作属性

只读

这部分属性只能读取,不能进行赋值修改

duration音频总时长

const audioDOM = document.getElementById("audio");
if (isNaN(audioDOM.duration)) {
    // 未加载时的操作
} else {
    // 已加载时的操作
}

paused是否暂停

const audioDOM = document.getElementById("audio");
if (audioDOM.paused == true) {  //如果是暂停状态
    audioDOM.play();  //播放音频
} else {              //如果正在播放
    audioDOM.pause(); //暂停
}

ended是否播放完毕

currentSrc音频链接

buffered已缓存范围

let audio = document.getElementById("audio");
let timeRanges = audio.buffered;
let num = 0;
/*获取已加载时长,然后除以歌曲时长,即可得到已加载比例*/
if(timeRanges.length > 0)
    num = parseInt(timeRanges.end(timeRanges.length - 1) * 100 / audio.duration);
if (num > 100)
    num = 100;
else if (num < 0)
    num = 0;

seekable可跳转范围

networkState网络范围

error发生错误

seeking是否移动或跳转播放进度

<audio id="audio" controls src="song.mp3" onseeking="seeking">
  您的浏览器不支持 audio 标签捏
</audio>

<script>
seeking:function(){
    const audioDOM = document.getElementById("audio");
    console.log(audioDOM.seeking);
}
</script>

可读写

这部分属性可以读取,也可以赋值修改

currentTime已播放时长

const audioDOM = document.getElementById("audio");
if (audioDOM.currentTime > 5) {
    audioDOM.currentTime -= 5;
} else {
    audioDOM.currentTime = 0;
}

volume音量

const audioDOM = document.getElementById("audio");
if (audioDOM.volume < 0.9) {
    audioDOM.volume += 0.1;
} else {
    audioDOM.volume = 1;
}

playbackRate播放速度

const audioDOM = document.getElementById("audio");
if (audioDOM.playbackRate >= 2)
    audioDOM.playbackRate = 0.5;
else
    audioDOM.playbackRate += 0.25;

标签属性控制

以下属性都会返回布尔值boolean,可读写设置对应的标签属性是否启用

const audioDOM = document.getElementById("audio");
audioDOM.controls = true;
if(audioDOM.loop == false){
    audioDOM.loop = true;
}

JS操作函数

play()播放

const audioDOM = document.getElementById("audio");
if (audioDOM.canPlay == true) {   //如果资源准备好可以播放
    if (audioDOM.paused == true)  //音频为暂停状态
        audioDOM.play();    //播放
    else
        audioDOM.pause();   //暂停
}

pause()暂停

load()加载


事件

加载生命周期

loadstart开始加载

durationchange时长改变

loadedmetadata元数据加载完毕

loadeddata数据开始加载

progress加载中

canplay可以播放

canplaythrough可以播放整个音频

其他事件

timeupdate已播放时长更新

waiting等待资源中

playing播放中

play播放

pause暂停

ended结束

volumechange音量改变

ratechange播放速率改变

error发生错误

  1. MatthewDoolo说道:

    ed med online: erectile dysfunction medicine online – cheapest ed pills

  2. MatthewDoolo说道:

    no prescription online pharmacy: canada prescription – best website to buy prescription drugs

  3. VlasovDomoiral说道:

    Connecting via feedback forms is an expressive manifestation of modern business communication, combining the top of tact and innovation. This approach provides companies a straight line to their consumers, allowing them to understand the nuances of user experience, garner constructive feedback, and, most, demonstrate that they are constantly hearing. Rather than traversing the cluttered scene of emails and advertising messages, response forms offer a streamlined space, setting the way for authentic dialogue and further involved conversations.

    Moreover, communicating to comment forms is a testament to a business’s dedication to ongoing betterment. Instead of functioning in a isolation, businesses get an precious perspective into their customers’ minds, revealing chances for development, betterment, and building firmer relationships. As consumer needs transform, this reciprocal interaction channel confirms that businesses stay not just pertinent but intimately linked to their audience’s constantly evolving tastes and worries. In the big design of things, it’s not just about gathering feedback; it’s about nurturing faith and solidifying bonds that endure the trial of time.

    Telgrm: @xrumers
    https://XRumer.cc/
    Skype: XRumer.pro

  4. Armandosed说道:

    http://onlinepharmacyworld.shop/# canadian pharmacy no prescription needed

  5. HeCax说道:

    Обращение в https://seo-saytov-v-msk.ru для поисковой оптимизации моего сайта, когда заметил падение трафика. Результаты не заставили себя ждать: компетентность команды, готовность помочь и видимый рост позиций. Рекомендую!

  6. DAMAC Lagoons说道:

    Discover exquisite villas and luxurious townhouses in the spectacular mega-development of Malta DAMAC Lagoons. Indulge in opulent living at unbeatable prices from renowned developer DAMAC Properties. Don’t miss out on your dream home in this unrivaled paradise.

  7. 1win924Cic说道:

    Букмекерская контора №1 в мире, советую 1win

  8. Marioarods说道:

    Based on God’s instructions, Abraham travelled to a place called Canaan where the Canaanites lived. There is no reason given for God’s choice of Palestine/Canaan for Abraham to journey to parables of jesus chart

回复 דירות דיסקרטיות בכפר סבא 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注