Play audio only once

hey everyone,
I have an audio starting 5 seconds into my project, however after numerous tries im still stuck with how to only play that sound once and not having it triggered a gazilion times…

any leads?

this is my code so far

var Smslyd = pc.createScript(‘smslyd’);

// initialize code called once per entity
Smslyd.prototype.initialize = function() {
this.secsSinceStart = 0;


// update code called every frame
Smslyd.prototype.update = function(dt) {
this.secsSinceStart += dt;

if (this.secsSinceStart >= 5) {"smslyd");


So, it looks like you’ll want to try setting the audio slot to only play once. The Dev API has almost everything you’ll need working with the PlayCanvas objects. Starting with entity, you can see sound is of type SoundComponent, going to that doc shows play() is using a SoundSlot to play sound, going to that doc shows you have a loop property available.

API | Entity - sound:
API | SoundComponent - slot:
API | SoundSlot - loop:

this.entity.sound.slot('smslyd').loop = false;

Hey @linelineline

After the this.secsSinceStart >= 5 condition is met and the line"smslyd"); is executed do you make this.secsSinceStart = 0 or something since this line will be executed after every frame if you dont make the variable this.secsSinceStart less then 5.

If you do the above, but still the sound is repeating, in the editor, on the sound component, can you make the sound slot property “loop” to false? It should be false if you dont want the sound to be looping.

thanks for the reply!
im not sure I understand what you mean by the first phrase, but I havent checked “loop” in the sound component, so shouldnt be looping?


The if (this.secsSinceStart >= 5) is met after 5 seconds are over, but after it is met, you have to reset this variable to something else so that the"smslyd"); is not executed every frame.

ah like that! thanks for the explanation.
how would I go about resetting the variable?

Make a boolean in initialize() function:
this.isSoundRun = false;

Then in your update:

Smslyd.prototype.update = function(dt) {
this.secsSinceStart += dt;
   if (this.secsSinceStart >= 5 && !this.isSoundRun) {
       this.isSoundRun = true;"smslyd");

awesome @Saad_Haider! thanks a million works like a charm :smiley:
if I wanted to repeat that sound numerous times at various intervals, let say at sec 5, sec7 and sec11 would I then just duplicate that bit and insert it one after another in the script?

To repeat at multiple intervals you can maintain an array having different intervals like this.intervals = [5,6,7,8]; and also have to maintain an index which increments after each sound is played and to reset the timer you can do this.secsSinceStart = 0 in the if condition.