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

/ 59,705评论 / 286530阅读 / 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. Если вы искали где отремонтировать сломаную технику, обратите внимание – сервис центр в барнауле

  2. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в челябинске

  3. Lazryix说道:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии по выгодным тарифам.
    084.vrn.ru/cgi-bin/firm.pl?IDF=3362

  4. Lazrehk说道:

    Здравствуйте!
    Мы готовы предложить дипломы любых профессий по невысоким тарифам.
    occ24.ru/preimushhestva-pokupki-diploma-3

  5. Lazrpos说道:

    Привет, друзья!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
    bigbizstuff.com/2024/08/18/diplom-737012dwbjp

  6. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт техники в барнауле

  7. Если вы искали где отремонтировать сломаную технику, обратите внимание – сервис центр в барнауле

  8. Jessesaf说道:

    The Cruciality of Oscillation Management Equipment in Machines
    Inside industrial contexts, equipment as well as rotational devices serve as the support of production. Yet, a of the highly common problems which might affect its operation along with lifetime is oscillation. Vibration could result in a series of challenges, ranging from minimized exactness along with productivity to increased deterioration, in the end bringing about expensive downtime as well as repairs. This is why vibration control equipment becomes critical.

    Why Vibration Management remains Critical

    Vibration inside equipment may cause various harmful consequences:

    Minimized Operational Effectiveness: Excessive resonance might result in discrepancies and unbalance, reducing the efficiency of the devices. This could result in slower production times as well as elevated power consumption.

    Elevated Erosion: Continuous vibrations speeds up overall erosion of mechanical parts, bringing about increased upkeep and the possibility of unexpected unforeseen malfunctions. This does not just increases maintenance expenses and decreases the durability of the existing equipment.

    Safety Concerns: Unmanaged resonance can bring significant dangers both to both the equipment and the operators. In extreme situations, severe cases, these could cause devastating system collapse, endangering workers and resulting in significant damage to the environment.

    Precision and Quality Concerns: For sectors that depend on precise production, such as production and aerospace, vibrations could lead to discrepancies in production, producing defective products and increased waste.

    Reasonably Priced Approaches for Oscillation Control

    Investing into vibration control systems remains not just a necessity but a prudent choice for any business any organization that uses machinery. The offered advanced vibration control systems are designed to reduce vibrations from various equipment or rotating machinery, guaranteeing uninterrupted along with efficient functioning.

    Something that sets our apparatus apart remains its economic value. We know the significance of cost-effectiveness in the competitive market of today, thus we provide top-tier vibration management solutions at prices that are reasonable.

    By choosing our systems, you are not just protecting your machinery and improving its performance you’re also putting resources in the long-term success of your operations.

    Conclusion

    Vibration control proves to be an essential factor of maintaining the operational performance, safety, and longevity of your equipment. Using our economical resonance mitigation apparatus, you can be certain your operations run smoothly, all manufactured items are of high quality, and your workers are protected. Don’t let resonance affect your business—invest in the correct apparatus today.

  9. Jessesaf说道:

    The Value of Resonance Management Equipment in Industrial Equipment
    Within production sites, machines along with spinning machinery act as the backbone of operations. Nonetheless, one of the most common issues which may impede the efficiency and lifespan is vibrations. Oscillation may lead to a variety of complications, ranging from minimized perfection along with effectiveness to increased deterioration, eventually leading to expensive downtime along with maintenance. This is the point where vibration control equipment becomes vital.

    Why Oscillation Control remains Critical

    Oscillation within machines can cause several harmful consequences:

    Decreased Production Efficiency: Excessive vibration could lead to misalignment and instability, lowering total efficiency of the devices. This might result in slower manufacturing speed as well as higher energy use.

    Elevated Wear and Tear: Constant oscillation speeds up total erosion of machinery parts, causing more regular maintenance and the potential of unexpected issues. Such a scenario doesn’t merely heightens maintenance expenses as well as decreases the lifespan of the existing devices.

    Protection Concerns: Unchecked vibration may pose major dangers both to both the equipment and the machinery and the workers. In, severe cases, it might result in devastating system collapse, endangering personnel and leading to widespread destruction to the environment.

    Exactness and Quality Concerns: For businesses that demand high accuracy, for example manufacturing and aviation, vibration could cause inaccuracies in the manufacturing process, causing defective products and greater waste.

    Economical Solutions to Vibration Management

    Investing in resonance control equipment proves not only a necessity but a prudent choice for any business that relies on machinery. The offered advanced vibration regulation equipment are engineered to eliminate vibrations from all mechanical systems and rotating equipment, providing seamless and productive processes.

    What sets our tools from others is its reasonable pricing. We understand the importance of affordability inside the competitive market of today, which is why we offer high-quality vibration regulation systems at rates that are reasonable.

    Opting for our equipment, you aren’t simply preserving your machines as well as improving its operational effectiveness you’re also putting investment into the sustained performance of your company.

    Final Thoughts

    Vibration management remains a necessary component of maintaining the effectiveness, security, and lifetime of your industrial equipment. With these reasonably priced oscillation control systems, one can make sure your operations operate seamlessly, all goods remain top-tier, and all personnel remain safe. Don’t let oscillation undermine your company—make an investment in the right equipment now.

  10. Если вы искали где отремонтировать сломаную технику, обратите внимание – выездной ремонт бытовой техники в барнауле

  11. Hi there mates, how is everything, and what you desire to say regarding this article, in my
    view its really remarkable in support of me.

  12. Sazrwpe说道:

    Привет, друзья!
    Купить документ института
    drug-stop.ru/sport/uventys-poslednii-raz-vyigravshii-ligy-chempionov-gde-oni-seichas

  13. Sazrnbq说道:

    Здравствуйте!
    Заказать документ о получении высшего образования
    promocodser.ru/students/educational-resources/

  14. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники

  15. Sazrjsr说道:

    Привет, друзья!
    Купить документ института
    statistwot.ru/farm/matilda-black-prince

  16. Если вы искали где отремонтировать сломаную технику, обратите внимание – сервисный центр в барнаул

  17. Kennethwilla说道:

    Экскурсия Долина Лотосов Анапа – Полёты на параплане в Анапе, Экскурсия Тамань

  18. Sazrijp说道:

    Рекомендации по безопасной покупке диплома о высшем образовании

    abris-zip.ru/company/personal/user/171/forum/message/1495/1505

  19. Sazrlwc说道:

    Реально ли приобрести диплом стоматолога? Основные этапы
    network-21596.mn.co/posts/65294298

  20. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники

  21. Oscarjef说道:

    Instagram drops your engagement and auto unfollows in order to force you to boost posts and spend money. We have tried a bunch of boosting https://www.authortalking.com/mastering-your-presence-on-social-media-the-instaboost-revolution/

  22. Jessesaf说道:

    The Value of Oscillation Control Apparatus in Industrial Equipment
    In manufacturing contexts, equipment and turning machinery serve as the backbone of output. However, a of the most widespread problems that can impede its performance and durability is vibration. Oscillation can lead to a variety of complications, such as reduced exactness and productivity to elevated deterioration, in the end bringing about pricey downtime and repairs. This is the point where vibration management tools is critical.

    Why Vibrations Mitigation remains Critical

    Resonance in industrial equipment can bring about various detrimental consequences:

    Minimized Operational Efficiency: Excessive vibration could cause discrepancies and imbalance, lowering overall performance with the machinery. This could lead to slower production schedules and increased energy consumption.

    Increased Damage: Ongoing oscillation hastens overall deterioration in equipment components, causing more frequent maintenance along with the possibility of unexpected issues. Such a situation not only raises maintenance expenses and reduces the lifetime for the devices.

    Safety Hazards: Excessive vibration may bring significant safety concerns to both the machinery and the operators. In severe cases, severe cases, it can cause cataclysmic system collapse, threatening workers along with resulting in significant damage to the premises.

    Accuracy and Quality Challenges: In sectors that demand high accuracy, such as manufacturing or aviation, vibrations can result in flaws in the production process, producing flawed products and greater waste.

    Reasonably Priced Solutions towards Vibration Control

    Investing in the vibration management equipment is not just necessary and also a prudent choice for any company that relies on machines. Our modern vibration regulation equipment work to built to remove resonance in any machine as well as spinning equipment, guaranteeing uninterrupted and effective performance.

    What distinguishes such systems from others is its affordability. It is recognized that the significance of affordability in the competitive market of today, which is why we have premium vibration regulation systems at rates that are affordable.

    Opting for our systems, you’re not only preserving your machines and enhancing its performance as well as putting resources in the long-term performance of your business.

    Final Thoughts

    Vibration control is a vital component in preserving the operational performance, protection, and lifetime of your machines. Using our affordable vibration control equipment, you can ensure that your processes run smoothly, all goods remain top-tier, and your employees remain safe. Never let resonance compromise your machinery—invest in the correct apparatus immediately.

  23. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт техники в барнауле

  24. What’s up, every time i used to check webpage posts here in the early
    hours in the daylight, for the reason that i like to find out more and more.

  25. It’s perfect time to make some plans for the future
    and it’s time to be happy. I’ve read this post and if I could I want to
    suggest you some interesting things or tips. Perhaps you can write next articles
    referring to this article. I wish to read more things about it!

  26. Definitely believe that that you said. Your favourite justification appeared to be at the web
    the easiest factor to have in mind of. I say to you, I certainly get annoyed while people think about worries that they
    plainly do not recognize about. You managed to hit the nail upon the highest as well as outlined out the whole thing without
    having side effect , other folks could take a signal. Will
    likely be again to get more. Thanks

  27. Howdy would you mind sharing which blog platform you’re using?
    I’m going to start my own blog soon but I’m
    having a difficult time choosing between BlogEngine/Wordpress/B2evolution and
    Drupal. The reason I ask is because your layout
    seems different then most blogs and I’m looking for something unique.
    P.S Apologies for being off-topic but I had to
    ask!

  28. Jessesaf说道:

    vibration analysis
    The Value of Oscillation Management Apparatus in Machinery
    Across industrial settings, devices along with spinning devices are the foundation of production. Yet, one of the commonly prevalent issues that could hinder its operation as well as durability is oscillation. Oscillation may lead to an array of issues, such as minimized exactness and efficiency to greater erosion, eventually causing pricey interruptions along with restoration. Such a situation is where vibration management systems becomes vital.

    Why Vibration Management remains Important

    Vibration inside machinery might result in multiple harmful consequences:

    Decreased Operational Productivity: Excessive resonance may cause misalignments as well as unbalance, reducing total productivity with such systems. Such might bring about slower production times and greater energy consumption.

    Increased Erosion: Continuous vibration hastens total wear and tear to machine components, resulting in more frequent upkeep and the potential of unexpected unexpected issues. Such a situation does not just increases operational costs and reduces the lifetime of your equipment.

    Security Dangers: Unmanaged oscillation could introduce major safety concerns to the machinery and the machinery as well as the operators. In, severe cases, such vibrations might result in catastrophic equipment breakdown, jeopardizing employees and resulting in widespread devastation to the environment.

    Accuracy and Manufacturing Quality Issues: For businesses which depend on high precision, including industrial sectors and aerospace, vibrations may cause discrepancies with the production process, producing defective products along with more waste.

    Economical Alternatives for Vibration Management

    Investing into resonance control apparatus is not just a necessity and also a wise choice for any business any company that uses machines. Our modern vibration control systems are engineered to eliminate vibrations within any machinery and rotating machinery, providing smooth along with effective performance.

    What sets our tools from others is its economic value. We know the significance of affordability in the modern competitive marketplace, thus we provide top-tier oscillation control tools at pricing that remain budget-friendly.

    Opting for our offerings, you’re not only protecting your machines and enhancing its efficiency but also putting investment in the long-term success of your company.

    Conclusion

    Vibration management remains an essential factor of maintaining the efficiency, safety, as well as durability of your machines. With our economical resonance mitigation apparatus, one can ensure your operations function efficiently, all goods remain top-tier, and your employees are protected. Don’t let resonance undermine your operations—invest in the right equipment now.

  29. Sazrjsa说道:

    Привет, друзья!
    Приобрести документ о получении высшего образования
    baigianghay.com/ta-canh-mot-buoi-sang-van-mau-hay-lop-6

  30. Удаление плесени Москва dezinfekciya-mcd.ru

    По вопросу дезинсекция квартиры Вы на верном пути. Мы являемся официальной дезинфекционной и санитарной службой города Москва. Все работники квалифицированы, техника и продукция одобрены Роспотребнадзором, поэтому не стоит беспокоиться, приглашая нас, всё пройдет в наилучшем виде. Также предоставляется гарантия до 5 лет на представленные услуги.

  31. Uazrxfq说道:

    Добрыйдень!
    Купить диплом любого ВУЗа.
    telegra.ph/kupit-diplom-v-sevastopole-08-13-6

发表回复

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