Categories: Snippets

Audio autoplay

window.addEventListener('load', () => {
    // noinspection JSUnresolvedVariable
    let audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'audio-autoplay.wav');
    xhr.responseType = 'arraybuffer';
    xhr.addEventListener('load', () => {
     let playsound = (audioBuffer) => {
      let source = audioCtx.createBufferSource();
      source.buffer = audioBuffer;
      source.connect(audioCtx.destination);
      source.loop = false;
      source.start();

      setTimeout(function () {
       let t = document.createElement('p');
       t.appendChild(document.createTextNode((new Date()).toLocaleString() + ': Sound played'));
       document.querySelector('.output').appendChild(t);
       playsound(audioBuffer);
      }, 1000 + Math.random()*2500);
     };

     audioCtx.decodeAudioData(xhr.response).then(playsound);
    });
    xhr.send();
   });

 

Share

Recent Posts

Selecting Elements in jQuery (jQuery Selectors)

To collect a group of elements, we pass the selector to the jQuery function using…

6 years ago

jQuery library Introduction

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is…

6 years ago

Adjust li width fit with ul width of the outer div/body

HTML:- [crayon-67a5b55637f46796156249/] CSS:- [crayon-67a5b55637f54274246023/] JavaScript:- [crayon-67a5b55637f56750565710/]  

6 years ago

Customize Input Box using jQuery

Prevent users typing special characters in text box, textarea, etc. [crayon-67a5b556380e0313996328/] ^[a-zA-Z]+$ Alphabets ^[a-zA-Z\s]+$ Alphabets…

6 years ago

JavaScript simple form validation with example

Any interactive web site has form input - a place where the users input different…

6 years ago

Clear the browser cache of CSS or JavaScript Using Javascript

[crayon-67a5b5563854e082231527/]  

6 years ago