简体   繁体   中英

How to detect when Autoplay fails in WaveSurfer.js?

I am accustomed to using the javascript media promise to detect when autoplay has failed as outlined here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes . But how do you detect an autoplay failure in WaveSurfer.js?

I've tried the error event but it doesn't appear to do anything in this case. What's even stranger is that the play event will fire regardless of whether it's 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');

See my jsfiddle for an example. If viewed through Chrome, autoplay will usually fail.

After searching around, I found that WaveSurfer JS uses WebAudio (an object called AudioContext is created). According to the Google page :

Key Point: If an AudioContext is created prior to the document receiving a user gesture, it will be created in the "suspended" state, and you will need to call resume() after a user gesture is received.

Then I realized, "hey, can't I add my own AudioContext to WaveSurfer??" Yes, I can. One of the WaveSurfer options is 'audioContext.'

Therefore, the idea is to create my own AudioContext, plop it into WaveSurfer, and read the state of the AudioContext to find out if it is suspended (auto-play failed) or not.

I have never done anything with Web Audio. But after digging around I came up with this:

// Fix up for 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM