Search code examples
javascripthtml5-audioweb-audio-api

Setter and extended property same name


I'm creating a class that deals with the Audio API to simplify some behaviors and wrap some functionalities that I want. One of the things that I need to do is, when set the volume value, I want the volume to change, but the point is that I'm extending audio API and volume is a value that already exists on that API.

I know that I can change the set volume() to setVolume() but this looks like a work arround and I'm wondering if there is a way to set that volume without this.

I try to make an "alias", something like vol, but with that alias I want to make volume as private and again I don't know if its possible to do this with and extended prop.

I try this too, but leads to a callback loop:

class MyAudio extends Audio {
  set volume(vol) {
    this.volume = vol;
  }
}

Is there a way to deal with this keeping the default behavior of Audio API?

[EDIT] One of the reasons that I want to do this is, since Audio API volume only accepts number as arguments, I want to sanitize string data coming as argument and set the volume with the parsed string.


Solution

  • Are you able to invoke the base class's volume property directly with super instead of this?

    See example below:

    class MyAudio extends Audio {
      get volume() {
        return (super.volume * 100).toFixed(0);
      }
      set volume(vol) {
        const value = Number(vol) / 100;
        super.volume = value;
      }
    }
    
    const myAudio = new MyAudio();
    myAudio.volume = "57";
    console.log('MyAudio volume', myAudio.volume);
    
    const audio = new Audio();
    audio.volume = 0.57;
    console.log('Audio volume', audio.volume);

    EDIT: Updated to include executable code snippet.