Tips for identifying Autoplay failure in WaveSurfer.js

While I've been using the javascript media promise to identify when autoplay has failed according to this guide: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes, I'm curious about how to detect an autoplay failure in WaveSurfer.js.

Despite attempting to use the error event, it doesn't seem to be effective in this scenario. Additionally, the play event consistently triggers regardless of whether the audio is actually playing or not.

https://jsfiddle.net/mcrockett/k985zjh2/18/

    var wavesurfer = WaveSurfer.create({
        container: '#waveform',
        waveColor: 'red',
        progressColor: 'purple'
    });

    function play() {
        wavesurfer.playPause();
    }

    wavesurfer.on('ready', play);

    wavesurfer.on('error', function(){
        console.log("does not get called when autoplay fails :(");
    });

    wavesurfer.on('play', function(){
        console.log("called even when autoplay fails");
    });




 wavesurfer.load('https://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');

Check out my jsfiddle for a demonstration. In Google Chrome, autoplay typically encounters failures.

Answer №1

Upon my quest for knowledge, I discovered that WaveSurfer JS utilizes WebAudio (triggering the creation of an object named AudioContext). As per the insights provided on the Google page:

The crux: If an AudioContext is initiated before the document receives a user gesture, it will be in a "suspended" state, requiring a 'resume()' call post receiving a user gesture.

Then a light bulb went off - why not integrate my own AudioContext into WaveSurfer? And indeed, it's possible. One of the customizable options in WaveSurfer is 'audioContext.'

Henceforth, the concept entails setting up my own AudioContext, integrating it seamlessly with WaveSurfer, and examining the AudioContext's state to determine if it's suspended (resulting in auto-play failure) or functional.

Despite my lack of experience in Web Audio, I crafted this solution after some exploration:

// Handling prefixing
window.AudioContext = window.AudioContext||window.webkitAudioContext;
var context = new AudioContext();

if(context.state === 'suspended')
  alert("auto-play failed!!");

var wavesurfer = WaveSurfer.create({
  container: '#waveform',
  waveColor: 'red',
  progressColor: 'purple',
  audioContext: context
});

https://jsfiddle.net/mcrockett/02azn6Lb/6/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The code for the Express app.get() method on the server is not being updated, although other parts of the

Recently, I encountered an issue with my node js and express server that is running on localhost. I made a change in the server code from: app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html'); }); To: app. ...

The socket.io client in my JavaScript code is failing to receive the necessary event

Currently, I am in the process of configuring a socket.io chat feature with an expressjs backend and sveltejs frontend. I have established a custom namespace named 'chat' where a new room is generated upon a 'join' request. My appro ...

When using React, the event.target method may unexpectedly return the innerText of a previously clicked element instead of the intended element that was

I have implemented a drop-down menu that triggers an event handler to return the selected option when it is clicked. Upon clicking on an option, I retrieve the inner text of that option using the event. The code snippet looks like this: event.target.inner ...

An alternative option for the location parameter in the post

$.post("location_example.php",{data:data},function(){ //performing some action }); I attempted to specify the full location path as "localhost:8888/myweb/data/index.php", but it does not seem to be posting anything. It appears that the parameter cannot ...

Yarn is incapable of locating node modules

It has been some time since I last used yarn / npm, and now I am facing an issue while trying to configure a basic express server with yarn and typescript. The problem is that yarn is not properly "linking" my node_modules directory. I suspect that I may ...

Creating "search result pages" with HTML, PHP, Javascript, and MySQL

Consider the scenario where you have a table with two columns: id and name, containing thousands of rows. You have a search engine that allows searching by free text, using the query: SELECT * FROM `table` WHERE `name` LIKE '%$search%' The res ...

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...

Designing a layout for a chat application that is structured from the bottom up

I'm currently in the process of designing a web application for a chat platform. I have access to an API that provides a list of messages: chatsite.com/api/thread/1/messages/ [ { "id": 2, "sender": { "id": 2, ...

Tips for accessing a unique window name in JavaScript

How can I make window.name persist between page refreshes? I need to use window.name to differentiate between multiple browser windows, allowing each one to display distinct data while sharing the same URL. However, my problem is that the value of window ...

Guide for utilizing regex to divide a string by various characters in the expression?

Apologies if the wording is unclear. I am currently looking for a solution on how to include a string match of multiple characters in my dynamic regex expression. The regex within my else statement successfully handles a single character input, now I am a ...

Adjust the settings of a CSS element

Apologies as I am still new to this and struggling to implement the correct code. I am attempting to modify the background color of a custom marker in leaflet.js. Essentially, I need to adjust the CSS element's value. I have the CSS code and how I am ...

A significant number of middleware packages, such as compress, are no longer provided as part of the

I recently added [email protected], [email protected], [email protected] and [email protected] (just to be safe). However, I am encountering this error message when trying to execute sails lift /Users/myuser/myproject/backend/node_modu ...

Formatting numbers in Angular 2 to include a space every three zeros in a money amount

Let's say I have the number 30000 and I want to format it as 30 000. What method should I use to achieve this? Here are more examples: 300000 -> 300 000, 3000000 -> 3 000 000. Just to clarify, this is not about using dots or commas, but rathe ...

Troubleshooting: jQuery AJAX .done() function failing to execute

Currently, I have a piece of code that is being utilized to dynamically load HTML into a CodeIgniter view: $.ajax({ type:"POST", url: "Ajax/getHtml", data: { u : conten ...

The styling of Material UI (MUI) buttons is not displaying correctly

Why are my MUI button components displaying differently than the documentation? I have not made any external .css file or theme changes except for the ones listed. I have also installed the Roboto font and configured the typography. I want any changes I ma ...

Show a variety of logos on the website based on the current date

I've been experimenting with displaying a unique logo on my website based on the current date (for example, showing a Christmas-themed logo during December). Here's what I have so far: <img class="logo" id="global_logo" sty ...

What is the best way to trigger a JavaScript function whenever a field reaches a specific length?

I need to update a function that currently triggers when the user clicks or tabs out of the employee_number field. My goal is for it to run whenever the length of the entered numbers reaches 6, without requiring the user to leave the field. When I attempte ...

Discovering digits within a given text using a specific pattern and modifying them using JavaScript

I have a series of text inputs containing numbers with a specific pattern throughout the text. I would like to identify all numbers with this pattern, recalculate them, and replace them in the text. .... val="2xf" ......... vc="2.6xf" ...... value= ...

What is the method for including a data attribute in the text of a cell using Datatables Editor?

When initializing datatables along with editor, I typically use the following code: columns: [ { data: "name", className: 'noEdit clickTextToOpenModal' }, In this line of code, I am able to set the className attribute. However, is i ...

Using Google App Engine with Stripe - Enable users to easily upload images for account identity verification directly through their browser using Javascript

After extensive research, I have been exploring how to enable direct browser uploads, particularly in the context of utilizing Stripe with Google App Engine, as discussed on this forum. The Stripe documentation also mentions the possibility of browser uplo ...