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

/ 32,906评论 / 113361阅读 / 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. RonaldSwobe说道:

    http://finasteride.store/# cost cheap propecia without insurance

  2. Davidfrify说道:

    cost of propecia for sale buy propecia without rx cost cheap propecia

  3. sasivtem说道:

    Хотите недорого снять жилье в СПб? Вам в этом точно поможет группа vk.com/komnataspb. Здесь многие находят себе уютное гнездышко, хотя поиск комнаты и соседей в Санкт-Петербурге – непростое дело. Выбирайте прямо сейчас актуальные предложения. Ищете снять комнату недорого? VK.com/komnataspb – известное сообщество, в котором состоит более 6000 человек. Рекомендуем вам обязательно вступить в него и нажать рассказать друзьям. Размещение объявлений на стене абсолютно бесплатно, мы тщательно следим за их качеством. Не забудьте ознакомиться с нашими правилами.

  4. lodemka.ru说道:

    индивидуальная консультация lodemka.ru

  5. vo_ntorg_ohSn说道:

    Воєнторг
    11. Качественные кобуры и чехлы для оружия
    металошукач баунти хантер https://voentorgklyp.kiev.ua/sporyadzhennya/metaloshukachi/ .

  6. vo_ntorg_gqSn说道:

    Воєнторг
    4. Снаряжение для выживания в экстремальных условиях
    армійський магазин армійський магазин .

  7. RonaldSwobe说道:

    https://lisinopril.network/# lisinopril 2.5 mg price

  8. WilliamRen说道:

    https://cytotec.club/# buy misoprostol over the counter

  9. Great site ! I recommend everyone to watch it!paris escort

  10. WilliamRen说道:

    http://ciprofloxacin.tech/# buy cipro cheap

  11. Matthewcon说道:

    Да, в приложении 1win существуют ограничения на вывод средств. Максимальная сумма вывода за транзакцию составляет 10 000 долларов, а ежедневный лимит вывода средств составляет 100 000 долларов 1win

  12. Davidfrify说道:

    generic propecia without insurance propecia pills buy propecia for sale

  13. 1win882Cic说道:

    Надёжная Букмекерская контора, всем советую 1win

  14. RonaldSwobe说道:

    https://finasteride.store/# buying generic propecia online

  15. 1winFoin787wette说道:

    Топовая Букмекерская контора в мире 1win

  16. RandallGuesE说道:

    buy cytotec over the counter: order cytotec online – Abortion pills online

  17. RobertMum说道:

    Ресурс, где можно купить надежные раковина 90 см по выгодным ценам.

  18. onavtyRet说道:

    На сайте https://muzzilka.ru/ послушайте качественную, яркую и приятную музыку на любой вкус и от лидирующих исполнителей. Она точно понравится вам своим звучанием, аранжировкой. Перед вами огромный выбор композиций, которые подарят положительные, яркие эмоции, настроят на позитив и помогут расслабиться. Кроме того, композиции помогут вернуться в прошлое и поностальгировать. Регулярно на портале появляются новинки, которыми сможет насладиться каждый. Слушайте музыку онлайн либо скачивайте на устройство.

  19. anlanUsaph说道:

    Вам нужна психологическая профессиональная помощь? Тогда обратитесь в центр «Доверие». Специалисты окажут нужную поддержку, им важно ваше хорошее состояние. Вы научитесь разбираться в своей психике и сможете понимать себя. Изменить свою жизнь к лучшему – вполне возможно. Ищете психологический центр? Ack-group.ru – сайт, где можно записаться на прием к ответственному и компетентному психологу в любое время. Также здесь имеется актуальная цена консультации опытного специалиста. Свяжитесь с нами прямо сейчас. Не нужно доводить до предела ситуацию!

  20. Davidfrify说道:

    buy zestoretic online lisinopril 20 mg price zestril 10 mg price

  21. RandallGuesE说道:

    cost cheap propecia without dr prescription: buying cheap propecia without prescription – buying generic propecia tablets

  22. NelsonBET说道:

    Discovered an article that might catch your interest – don’t miss it! http://forum.kam.su/member.php?u=5734

  23. Davidfrify说道:

    cost cheap propecia price propecia otc cost of propecia without insurance

  24. RandallGuesE说道:

    where can i buy nolvadex: tamoxifen joint pain – tamoxifen and grapefruit

  25. WilliamRen说道:

    https://lisinopril.network/# buy lisinopril 40 mg tablet

  26. Scottvaw说道:

    Understanding COSC Certification and Its Importance in Horology
    COSC Accreditation and its Rigorous Standards
    COSC, or the Official Swiss Chronometer Testing Agency, is the authorized Switzerland testing agency that attests to the accuracy and precision of timepieces. COSC validation is a sign of excellent craftsmanship and dependability in timekeeping. Not all watch brands pursue COSC accreditation, such as Hublot, which instead adheres to its own stringent standards with movements like the UNICO calibre, attaining comparable accuracy.

    The Science of Precision Chronometry
    The core mechanism of a mechanized timepiece involves the spring, which provides power as it loosens. This system, however, can be susceptible to external elements that may influence its precision. COSC-accredited movements undergo demanding testing—over 15 days in various conditions (five positions, 3 temperatures)—to ensure their resilience and dependability. The tests evaluate:

    Mean daily rate accuracy between -4 and +6 seconds.
    Mean variation, maximum variation levels, and effects of temperature variations.
    Why COSC Validation Is Important
    For timepiece enthusiasts and connoisseurs, a COSC-certified watch isn’t just a piece of technology but a testament to lasting quality and accuracy. It signifies a timepiece that:

    Offers excellent dependability and accuracy.
    Provides guarantee of superiority across the entire construction of the watch.
    Is apt to hold its worth more effectively, making it a wise investment.
    Popular Chronometer Brands
    Several renowned brands prioritize COSC validation for their timepieces, including Rolex, Omega, Breitling, and Longines, among others. Longines, for instance, presents collections like the Archive and Spirit, which highlight COSC-validated mechanisms equipped with advanced materials like silicon equilibrium springs to improve resilience and performance.

    Historical Context and the Development of Chronometers
    The idea of the timepiece originates back to the requirement for exact timekeeping for navigational at sea, highlighted by John Harrison’s work in the eighteenth cent. Since the official establishment of Controle Officiel Suisse des Chronometres in 1973, the accreditation has become a benchmark for judging the precision of high-end watches, sustaining a legacy of superiority in horology.

    Conclusion
    Owning a COSC-certified watch is more than an visual selection; it’s a commitment to excellence and precision. For those appreciating accuracy above all, the COSC certification offers peace of mind, guaranteeing that each validated watch will operate dependably under various conditions. Whether for personal satisfaction or as an investment decision, COSC-certified watches distinguish themselves in the world of horology, maintaining on a tradition of meticulous chronometry.

  27. 에그벳 슬롯说道:

    qiyezp.com
    그런데 지금… 프로 타이틀 시험에 대한 뉴스가 도처에서 논의되고 있습니다.

  28. Davidfrify说道:

    get cheap propecia tablets cost propecia without insurance buying propecia without a prescription

  29. RandallGuesE说道:

    does tamoxifen cause joint pain: nolvadex gynecomastia – tamoxifen rash

  30. RandallGuesE说道:

    tamoxifen hip pain: is nolvadex legal – tamoxifen mechanism of action

  31. WilliamRen说道:

    http://cytotec.club/# purchase cytotec

  32. 1winFoin788wette说道:

    Лучшая Букмекерская контора в мире 1win

  33. 1win883Cic说道:

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

  34. Davidfrify说道:

    lisinopril 12.5 tablet lisinopril 3760 zestril online

  35. JosephMUt说道:

    На сайте https://penza-evakuator.ru/ воспользуйтесь услугами легкового, грузового эвакуатора. В компании вас ожидают небольшие расценки – от 2 500 рублей. Оплатить услугу вы сможете любым, наиболее комфортным для себя способом. Работа происходит в круглосуточном режиме. Также можно воспользоваться и такими услугами, как: эвакуатор спецтехники, междугородняя эвакуация. Техника подается за считанные минуты, даже несмотря на ваше местоположение. Вас ожидает привлекательная стоимость.

  36. aodyuDox说道:

    Зайдите на сайт Лишь Вам https://lishvam.ru/ который является электронной площадкой для размещения товаров и услуг. Для покупателей ассортимент более чем из 100.000 товаров, а доставка осуществляется по всей России. Ознакомьтесь с каталогом и выбирайте товары по выгодным ценам, получайте бонусы за покупки.

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

  38. dottevneome说道:

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

  39. WilliamTom说道:

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

  40. WilliamRen说道:

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

回复 נערות ליווי בתל אביב 取消回复

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