Printable Version of Topic

Click here to view this topic in its original format

HTMLHelp Forums _ Client-side Scripting _ How to play Audio file?

Posted by: Morkus Sep 21 2021, 09:36 AM

Hello,

I'm trying to get some basic HTML/JS code working to play an audio file.

What I have so far isn't working and I can't find a complete example. I'm using FireFox, Safari, and Chrome as the destination browsers.

Can someone explain what I need to do to get this HTML/JS to work?

Ideally, I want to put "VCR"-type controls to "play", "pause", and "rewind".

CODE
<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        let x = document.getElementById("audio_file");
        document.getElementById("audio_file").controls = true;

        function playAudio()
        {
            x.play();
        }

        function pauseAudio()
        {
            x.pause();
        }
    </script>
    <meta charset="UTF-8">
    <title>Play Audio</title>
</head>
<body>
<div id='audio_file'>
    <audio>file:///Users/.../Desktop/myaudio.mp3</audio>
</div>
<button type="button" onclick=playAudio();>Play</button>
</body>
</html>

Posted by: Christian J Sep 21 2021, 01:06 PM

Hello!

No personal experience with AUDIO, but it seems the script tries to give player controls to the DIV element, which is incorrect. It's the AUDIO element that uses those controls. There are some other issues as well, see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio for code examples.

Posted by: Morkus Sep 21 2021, 01:13 PM

Thanks very much.

I finally got it working! smile.gif

Appreciate your reply.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)