Playing back sound using HTMLMediaElement

I am trying to download and play an audio file in chrome successfully, but I cannot play it back:

audio = new Audio('http://mathweirdo.com/bingo/audio/buzzer.mp3'); audio.playbackRate = -1; audio.currentTime = audio.duration; // I have tried ommiting this line audio.play() 

This does not cause a sound, and only one timeupdate event timeupdate .

+5
source share
1 answer

Using negative values ​​is not currently supported, so you have to manually load and discard buffers.

Please note that this will require a CORS-enabled sound source (one that is missing in the example, so I couldn’t set up a live demo). Here is one way to do this:

  • Upload data via AJAX (CORS required)
  • Let the browser parse the buffer into a sound buffer
  • Get channel buffer (links)
  • Reverse Buffer (s)
  • Initialize sound buffer and play

This, of course, limits you to the fact that you can no longer use the Audio element. You will need to support the necessary functions by adding controls and code for them.

 // load audio as a raw array buffer: fetch("http://mathweirdo.com/bingo/audio/buzzer.mp3", process); // then process the buffer using decoder function process(file) { var actx = new (window.AudioContext || window.webkitAudioContext); actx.decodeAudioData(file, function(buffer) { var src = actx.createBufferSource(), // enable using loaded data as source channel, tmp, i, t = 0, len, len2; // reverse channels while(t < buffer.numberOfChannels) { // iterate each channel channel = buffer.getChannelData(t++); // get reference to a channel len = channel.length - 1; // end of buffer len2 = len >>> 1; // center of buffer (integer) for(i = 0; i < len2; i++) { // loop to center tmp = channel[len - i]; // from end -> tmp channel[len - i] = channel[i]; // end = from beginning channel[i] = tmp; // tmp -> beginning } } // play src.buffer = buffer; src.connect(actx.destination); if (!src.start) src.start = src.noteOn; src.start(0); }, function() {alert("Could not decode audio!")} ) } // ajax loader function fetch(url, callback) { var xhr = new XMLHttpRequest(); try { xhr.open("GET", url); xhr.responseType = "arraybuffer"; xhr.onerror = function() {alert("Network error")}; xhr.onload = function() { if (xhr.status === 200) callback(xhr.response); else alert(xhr.statusText); }; xhr.send(); } catch (err) {alert(err.message)} } 
+6
source

Source: https://habr.com/ru/post/1216013/


All Articles