0
votes

On my site, I have an iframe element that is playing music (I cannot use a audio element in this instance) and I would like to be able to change the volume using a slider.

I have tried the following:

HTML:

<iframe src="bg.mp3" allow="autoplay" style="display:none" id="iframeAudio"></iframe>
<input id="vol-control" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)" />

Javascript:

var iframe = document.getElementById('iframeAudio');
iframe.setVolume(val / 100);

However, I get the following error in the console:

Uncaught TypeError: iframe.setVolume is not a function

How can I do this?

1
This feature is unfortunately not supported in most browsers: developer.mozilla.org/en-US/docs/Mozilla/Gecko/Chrome/API/โ€ฆ You might be better off using the HTML5 audio tag or webaudio rather than an iframe to play the sound. โ€“ jcbdrn

1 Answers

0
votes

You can do this in a different way with a small trick like this:

you can upload the video you want to your YouTube channel then

  1. head over the video you want on the YouTube to grab the video ID, you will find it after v= like this ๐Ÿ‘‡

enter image description here

So in our example here the video ID is _cB8CE_Q3Yk

  1. To control the volume or any other property ๐Ÿ‘‡
<!DOCTYPE html>
<html>
<head>
    <title>YouTube API</title>
    <!--to load YouTube "iframe_api" asynchronously-->
    <script async src="https://www.youtube.com/iframe_api"></script>
</head>
<body>
    <div id="div_YouTube"></div>
</body>

<script>
    function onYouTubeIframeAPIReady() {

        var player;

        player = new YT.Player('div_YouTube', {
            videoId: '_cB8CE_Q3Yk',   // ๐Ÿ‘ˆ video id.
            width: 560,
            height: 316,
            playerVars: {
                'autoplay': 1,
                'controls': 1,
                'showinfo': 0,
                'modestbranding': 0,
                'loop': 1,
                'fs': 0,
                'cc_load_policty': 0,
                'iv_load_policy': 3
            },
            events: {
                'onReady': function (e) {
                  e.target.setVolume(100); // For max value, set value to 100.
                }
            }
        });
    }
</script>
</html>

And for more info about IFrame Player API:

  1. https://developers.google.com/youtube/iframe_api_reference
  2. https://www.encodedna.com/javascript/youtube-api-embed-video-with-mute-sound-setvolume-onstatechange-event.htm