Fade Audio

Hello!

I’m looking to fade audio when a UI button is clicked and I’m hoping someone could give me some pointers. Thank you in advance!

Hi @RumaiIndustries,

One way to do this is to use the PlayCanvas tween library. It allows you to tween animate any kind of value:

https://developer.playcanvas.com/en/tutorials/tweening/

From there you can get a reference to your sound component and set the volume using the tween from 1 to 0, or vice versa.

https://developer.playcanvas.com/api/pc.SoundComponent.html#volume

2 Likes

Hello @Leonidas!

I took a look at the links you provided, and messed around a bit.
I sadly can’t fully understand how to do this though, so I was wondering if you knew about any examples that implemented something similar.

Edit: I found this project in the developer manual and I was hoping you could give me a quick example on how to enable the sound curve when a button is clicked. I understand if you’re too busy though!

Sound volume control using curve | Learn PlayCanvas

Nice, you can check this UI buttons tutorial:

https://developer.playcanvas.com/en/tutorials/ui-elements-buttons/

Then on the on click event method you can add some logic to enable the entity that holds your sound curve. Have it initially disabled, and do something along these lines:

this.entity.button.on('click', function(event) {
    this.app.root.findByName('Sound Curve Entity').enabled =  true;
}, this);

Hope that helps!

Thanks for the quick response!

This is exactly what I’m looking for, but I’m getting an error.

This is the Sound Curve script:

var AudioCurve = pc.createScript('audioCurve');

AudioCurve.attributes.add("volumeCurve", {type: "curve", title: "Volume Curve"});

// initialize code called once per entity
AudioCurve.prototype.initialize = function() {
    // Get a reference to a soundslot
    this.slot = this.app.root.findByName("Box").sound.slot("sfx");    
    var assetId = this.slot.asset;
    
    // Find the duration of the audio sample directly from the asset resource
    this.duration = this.app.assets.get(assetId).resource.duration;
};

// update code called every frame
AudioCurve.prototype.update = function(dt) {
    for (var i = 0; i < this.slot.instances.length; ++i) {
        var instance = this.slot.instances[i];
        
        // Change the volume of the audio based on the value of the curve at 
        // the current play time of the audio
        instance.volume = this.volumeCurve.value(instance.currentTime / this.duration);
    }  
};

It’s giving me an error in the script, it says it can’t find the slot.