jqueryiphoneaudiosafarihtml5-audio

Audio tag on Iphone (Safari)


I am making a barcode scanning web application. I chose QuaggaJS as barcode scanning library. I want to play a beep sound when the barcode is scanned. I have used audio tag and using JQuery to play the sound on detection of barcode. It works for all the broswers such as Chrome, Edge, FireFox but it does not work well on Safari. Other events also triggers the play() unexpectedly. Sometimes it works and sometimes it does not.

Code:

Audio

<audio id="beepSound" controls>
    <source src="beep.mp3" type="audio/mp3"/>
    <source src="beep.ogg" type="audio/ogg" />
</audio>

JQuery :

Quagga.onDetected(function (result) {
    $('#beepSound').get(0).load();
    $("#beepSound").get(0).play();
    Quagga.stop();
});

I have tried most of the solutions provided on StackOverflow for this issue but none seems to work. Even tried using this Html 5 Audio is not working in iphone safari browser but it did not work.


Solution

  • I removed the Audio tag, the fake click method just does not work, so I had to use a different approach to this and here is the JS Function that made this beep sound happen:

      function playBeepSound() {
        const AudioContext = window.AudioContext || window.webkitAudioContext;
        const audioContext = new AudioContext();
        const oscillator = audioContext.createOscillator();
        oscillator.type = 'sine'; //other waveforms (e.g., 'square', 'sawtooth')
        oscillator.frequency.setValueAtTime(1000, audioContext.currentTime); // Adjust frequency as needed
        oscillator.connect(audioContext.destination);
        oscillator.start();
        oscillator.stop(audioContext.currentTime + 0.1); // Play for 0.1 seconds
    }
    

    Calling the function :

    Quagga.onDetected(function (result) {
       playBeepSound()
       Quagga.stop();
    });