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

/ 32,866评论 / 113189阅读 / 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. Scottvaw说道:

    Understanding the complex world of chronometers
    Understanding COSC Certification and Its Importance in Horology
    COSC Validation and its Rigorous Criteria
    Controle Officiel Suisse des Chronometres, or the Controle Officiel Suisse des Chronometres, is the official Switzerland testing agency that verifies the precision and precision of timepieces. COSC validation is a symbol of excellent craftsmanship and trustworthiness in timekeeping. Not all watch brands seek COSC accreditation, such as Hublot, which instead adheres to its proprietary stringent standards with movements like the UNICO calibre, achieving equivalent precision.

    The Art of Exact Timekeeping
    The core mechanism of a mechanized watch involves the spring, which supplies energy as it unwinds. This system, however, can be susceptible to environmental factors that may influence its accuracy. COSC-accredited mechanisms undergo strict testing—over fifteen days in various circumstances (5 positions, 3 temperatures)—to ensure their durability and reliability. The tests evaluate:

    Typical daily rate precision between -4 and +6 secs.
    Mean variation, maximum variation rates, and effects of thermal variations.
    Why COSC Accreditation Is Important
    For watch enthusiasts and connoisseurs, a COSC-certified watch isn’t just a item of tech but a proof to enduring quality and precision. It symbolizes a timepiece that:

    Offers outstanding reliability and accuracy.
    Provides assurance of quality across the complete construction of the timepiece.
    Is likely to hold its worth more efficiently, making it a smart choice.
    Famous Chronometer Brands
    Several renowned brands prioritize COSC certification for their timepieces, including Rolex, Omega, Breitling, and Longines, among others. Longines, for instance, provides collections like the Record and Spirit, which feature COSC-accredited mechanisms equipped with advanced materials like silicon equilibrium suspensions to improve durability and performance.

    Historical Context and the Evolution of Chronometers
    The concept of the timepiece dates back to the need for precise chronometry for navigation at sea, emphasized by John Harrison’s work in the 18th century. Since the official foundation of Controle Officiel Suisse des Chronometres in 1973, the validation has become a yardstick for judging the accuracy of luxury timepieces, sustaining a tradition of excellence in watchmaking.

    Conclusion
    Owning a COSC-certified watch is more than an visual selection; it’s a dedication to quality and precision. For those valuing accuracy above all, the COSC accreditation offers peace of mind, ensuring that each validated watch will perform dependably under various conditions. Whether for individual contentment or as an investment decision, COSC-validated timepieces stand out in the world of horology, bearing on a tradition of precise chronometry.

  2. dottevneome说道:

    Геоинтеллект – платформа, которая обладает множеством необходимых функций для сбора информации о населении, розничных конкурентах и др. Наши специалисты имеют достойный опыт работы аналитики геоданных. Они используют наилучшие научные практики, а именно: статистика, экономика, городское, также социальное планирование. https://geointellect.com – сайт, где можете в любое удобное время детально ознакомиться с кейсами о геомаркетинге. У нас имеется много удачных проектов во всех городах РФ, Узбекистана и Казахстана для сотен клиентов. Трудимся для вас!

  3. WilliamTom说道:

    Изучение английского языка по сериалам – отличный метод улучшать язык. Телесериалы для базового уровня помогут овладеть базовые фразы, а для продвинутого – увеличить лексический запас. Субтитры в телесериалах на английском помогут в понимании контекста. Как учить английский по сериалам? Просто погружайтесь в английский язык смотря и слушая любимые сериалы! Смотреть и изучать английский языка можно тут https://serialy-na-anglijskom.pp.ua/

  4. WilliamRen说道:

    https://ciprofloxacin.tech/# buy cipro online

发表回复

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