How can I use my slider to adjust the volume of my device?

Viewed 16

I am trying to use a slider to adjust the volume of a project I am working on and I cannot find a way to sync the slider to my computers settings. If that is impossible is there a way to convert the value, and divide it so that it would vary between 0.0 and 1 as a decimal to then input it separately into the code?

Here is the volume controller and the place where the music gets recognized.

<script src="https://sdk.scdn.co/spotify-player.js"></script>
    <script>
        window.onSpotifyWebPlaybackSDKReady = () => {
            const token = '';
            const player = new Spotify.Player({
                name: 'Web Player',
                getOAuthToken: cb => { cb(token); },
                volume: 0.5
            });

And here is the slider

<div class="slidecontainer">
  <input type="range" min="0" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="VolumeValue"></span></p>
</div>

<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("VolumeValue");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>

If you haven't guessed already I am fairly new to programming so any help would be appreciated.

1 Answers

When you're declaring your Spotify player variable inside of the onSpotifyWebPlaybackSDKReady callback, it's only visible there and you can't call the setVolume method somewhere else to apply slider values.

One option would be to store the player variable in the window object:

window.onSpotifyWebPlaybackSDKReady = () => {
    window.spotifyPlayer = new Spotify.Player({
        ...
    })
};

This would allow you to access it in a slider change event handler:

slider.oninput = function() {
    // Assuming you stick to your range 0..100, then this would calculate values 0..1
    window.spotifyPlayer.setVolume(this.value / 100);
}
Related