My Audio

How to Play Audio After The Page Loads in HTML With JavaScript

Hello developer, today I am going to show you how to play audio after page load in JavaScript. In many cases, it is seen that we need to play the audio file only after the webpage gets loaded. Because most of the times, we don’t wanna play the audio file before the webpage getting loaded.

Update: In the recent updates of Chrome, you might face difficulties for autoplay as you will need to use

You may get error like this: Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.

Google chrome is very much strict to defense the noise autoplay on a webpage.

Play this video tutorial to learn more

Play Audio After The Page Loads in JavaScript

Note that: For the recent updates of chrome and some other browsers you should try this:

Navigate to Google Chrome Settings, Search permissions and give audio permission,

You can also add your page link in allow section

sound allow in chrome

(Mayuresh Deshmukh commented on this post)

So before showing you that directly I would like to show you how audio file is played in HTML.

So we need to remove the autoplay attribute first. Then we gonna add our JavaScript function to play the audio on page load.

So our full code will look like this

      window.onload=function() 

will run this function after page load.

document.getElementById("my_audio").play();

Here document.getElementById() method is responsible for getting the audio file by its id.

Later, play() method is used to play the audio file.

Special Note: The audio tag is used in the body tag not in the head tag, because if you insert it into the head tag the browser will automatically load the media data in the body section. You can use your browser’s inspect option to see what happens if you put the audio tag in the head tag.

So it’s better to put the audio tag in the body tag.

Using this JavaScript function you can easily play the audio file after page loading.

Feel free to write in the comment section and watch the video embedded on this page to learn how to set the time delay to play your audio file on the webpage.

Источник

JavaScript – How to Play Audio?

While creating an entertainment-based website, there can be a requirement to include audio to clear out the user’s understanding. For instance, appending audio relevant to the added content. In such cases, playing audio in JavaScript is of great aid in engaging the audience, thereby increasing the traffic, and improving the user’s interaction with the site.

This article will describe the approaches to play audio in JavaScript.

How to Play Audio in JavaScript?

To play audio in JavaScript, apply the below-stated approaches:

Method 1: Play Audio Using the “play()” Method in JavaScript.

The “play()” method plays the current audio, and the “pause()” method stops the audio being played. These methods can be applied to play and pause the associated audio with the help of a user-defined function.

Example

Let’s overview the below-stated example:

let x = document. getElementById ( ‘mySound’ ) ;
functionplayAudio ( ) {
x. play ( ) ;
}
functionpauseAudio ( ) {
x. pause ( ) ;
}

  • Firstly, include an “ ” element along with the “audio” attribute that allows to include the play, and pause controls.
  • After that, include a “ ” element to attach the audio file and specify the type of the file in the “type” attribute.
  • In the next step, create two buttons with attached “onclick” events invoking the stated functions to play and pause the audio file.
  • Now, in JavaScript code, fetch the audio file by its “id” using the “getElementById()” method.
  • Then, define a function named “playAudio()”.
  • In its definition, apply the “play()” method to play the associated audio.
  • Likewise, declare a function “pauseAudio()”, and the “pause()” method in its definition will similarly pause the corresponding audio.

In the output, it can be seen that the included audio is being played and paused properly.

Method 2: Play Audio Using autoplay Property in JavaScript

In this method, the “autoplay” property enables the audio as soon as it is loaded. This property can be utilized to play the corresponding audio upon being loaded.

Example

The below-stated example illustrates the stated concept:

let myAudio = new Audio();
functionplayAudio() alert(‘The audio will start playing now.’)
myAudio.src = ‘sound.mp3’;
myAudio.autoplay = true;
myAudio.loop = true;
>
functionpauseAudio() alert(‘Now the audio will pause’)
myAudio.pause();
>

  • Likewise, create two buttons with an “onclick” event redirecting to the functions playAudio() and pauseAudio(), respectively.
  • In the JavaScript part of the code, create a new audio object with the help of the “new” keyword and the “Audio()” constructor, respectively.
  • After that, define a function named “playAudio()”.
  • In its definition, it generates an alert to notify the playing of audio.
  • In the next step, the “src” attribute specifies the audio path.
  • The “autoplay” property indicates that the audio will play when the function becomes invoked.
  • loop” property defines that the audio file will be played till the next action.
  • Lastly, similarly, declare a function named “pauseAudio()”.
  • In its definition, display an alert dialogue box referring to a notification before the audio is paused.

The above output indicates that upon clicking the buttons, the audio has been played and paused appropriately.

Conclusion

To play audio in JavaScript, apply the “play()” and “pause()” methods in combination or the “autoplay” property. The former methods can be implemented to play and pause the associated audio file with the help of controls, respectively. The latter approach can be applied to play and pause the audio file as soon as the corresponding functions are invoked. This article discussed the approaches to play audio in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Воспроизведение звука на JavaScript

Воспроизведение звука на JavaScript

Я долго думал, куда отнести эту статью, то ли к HTML5, то ли к JavaScript. В конце концов, я решил отнести именно ко второму разделу, так как звуки чаще всего делают при возникновении какого-то события, а это уже относится к скриптам. Таким образом, в этой статье Вы узнаете, как воспроизвести звук на JavaScript.

Для начала базовая теория. Для добавления аудио на страницу служит тег audio:

Таким образом, можно добавить какую-нибудь фоновую музыку на сайт. Атрибут src отвечает за путь к воспроизводимому файлу, а атрибут autoplay отвечает за автоматическое воспроизведение файла при загрузке страницы. Теперь разберём, как сделать звуковую обработку события на JavaScript. Допустим, будем обрабатывать клик мышью по тексту:

Осталось лишь сделать функцию soundClick():

function soundClick() var audio = new Audio(); // Создаём новый элемент Audio
audio.src = ‘click.mp3’; // Указываем путь к звуку «клика»
audio.autoplay = true; // Автоматически запускаем
>

Таким образом, можно обработать звуком любое возникающее событие на странице. Единственное, что Вы должны чётко понимать — работать это всё будет только в современных браузерах, где есть поддержка HTML5. Впрочем, все используемые на данный момент браузеры (за очень редким исключением), его поддерживают в достаточно высокой степени, поэтому с воспроизведением звуков и музыки через тег audio проблем не возникнет.

Создано 02.12.2013 12:58:51

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 14 ):

    Здравствуйте , Уважаемый Русаков Михаил. Не подскажите как сделать , чтобы на сайте был не видимый контент , а при клике он появлялся и еще раз при клике опять закрывался. P.S.Поискал на сайте не нашел.

    Здравствуйте, Андрей. Делается это с помощью jQuery.

    Я не знаю толком jQuery. Можете написать?

    Зачем использовать библиотеку для двух строчек кода, который можно написать на ванильном JS?

    Не на вкус и цвет, а оптимизация. Зачем ради такой лёгкой задачи подключать тяжеловесную библиотеку JQuery?

    Здравствуйте Михаил, не желаете ли вы зайти на фри ланс и вспомнить о конкурсе который создавали, и должны были объявить победителя 4 дня назад?

    Михаил, есть одно замечание по доработке Вашего сайта, дело в том, что я забыл пароль, попытался восстановить его по почте. Но я и логин забыл тоже, но в почте не приходит логин, только имя, по которому зайти нельзя, логин можно посмотреть только тогда, когда заходишь на сайт. И нельзи ли сделать перенос караток в комментариях, а то иногда неудобно читать тот код, что присылают у вас на сайте в комментариях. И еще вопрос, нету у вас на сайте php — java скрипта новогодней елки, типо чтобы тикали часики сколько осталось до нового года, только опиралось на серверное время сервера. Ну можно еще каких-нибудь плюшек. Заранее спасибо.

    Здраствуйте, как можно сделать на сайте отдельную категорию для музыки.

    Здравствуйте, Михаил! А у меня вот такой вопрос — как сделать, что бы музыка воспроизводилась в фоновом режиме при клике на картинку. Без отображения аудиоплейера. Пусть это сработает не во всех браузерах, но это уже вторая беда.

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Читайте также:  Type conversion to string in java
    Оцените статью