How to ask Audio Autoplay permission in the browser(safari) with javascript

Viewed 2473

I am getting this error in Safari(MAC),

enter image description here

i am implementing a feature that triggers audio alert when a buyer sends a request to the seller. I am able to play muted audio but it show error when it is being played Unmuted. I want to ask is there any way we can ask users to allow audio play permissin as like we ask geolocation or camera/mic access permission with JavaScript. Any help would be appreciated.

This is my code:

window.MutedAudioPlayed = false;
        window.MyAudio = new Audio("https://XXXX.com/input_sound.mp3");
        window.MyAudio.preload = 'auto';
        window.MyAudio.muted = true;
        window.MyAudio.play().then(function (event) {
            window.MutedAudioPlayed = true;
            console.log('Audio MutedAudioPlayed: ', window.MutedAudioPlayed);
        }).catch(function (error) {
            window.MutedAudioPlayed = false;
            console.log('Audio Play Error: ', error.message);
        });

        window.MyAudio.muted = false; 
        window.MyAudio.play().then(function (event) {
            console.log("Audio Play: ", event);
        }).catch(function (error) {
            console.log('Audio Play Error: ', error.message);
        });
1 Answers

From what we figured so far, you can do the following:

  1. Request user the permission for audio (that usually stands for microphone, but also works for sounds)
  2. Load your sound file and use AudioBuffer to play it, see below for example.
const audioContext = new (window.AudioContext || window.webkitAudioContext)();

navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then(() => {
        const source = audioContext.createBufferSource();
        source.addEventListener('ended', () => {
            source.stop();
            audioContext.close();
        });

        const request = new XMLHttpRequest();

        request.open('GET', '/path-to-sound.mp3', true);
        request.responseType = 'arraybuffer';
        request.onload = () => {
            audioContext.decodeAudioData(
                request.response,
                (buffer) => {
                    source.buffer = buffer;
                    source.connect(audioContext.destination);
                    source.start();
                },
                (e) => {
                    console.log('Error with decoding audio data' + e.message);
                });
        }

        request.send();
    })
    .catch(reason => console.error(`Audio permissions denied: ${reason}`));

This approach has several drawbacks, though:

  1. You can't play sound in the background
  2. If you do that, the sounds would be queued in Safari and played when tab/window is active again
Related