Controlling audio with scripts

This tutorial explains how to control the audio in your game using scripts. You can play, stop, pause and resume sound effects and songs in your game when certain events occur by controlling the sound with code. This video explains how to do that and if you scroll down you will find the sample code.

The following sample code is used to control an audio source/slot called “song” that is attached to the same entity that the script is attached to. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                this.entity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                this.entity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

The following sample code is used to control an audio source/slot called “song” that is attached to a Sound entity called “mySound“. The script can be attached to any other entity in the game scene. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            // creates variable for audio entity
            var AudioEntity = app.root.findByName('mySound');
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                AudioEntity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                AudioEntity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/