F
F
fif2022-02-08 18:45:43
typescript
fif, 2022-02-08 18:45:43

How to loop music?

I have a Music class that plays music when the window is clicked. I have 2 tracks, they should start like this: the first track plays first, and after that the second track plays (looping). That is, after the first track, the second should be constantly repeated.
Here is the class:

export const soundVal = "50";
export let musicVal = "50";

export function changeVal(val: string) {
    musicVal = val;
}

const musicStart = new Audio();
musicStart.src = "audio/start.mp3";
musicStart.volume = 0.5;

const musicMain = new Audio();
musicMain.src = "audio/main.mp3";
musicMain.volume = 0.5;

export class Music {
    constructor() {
        this.startMusicPlay = this.startMusicPlay.bind(this);
    }

    public changeMusicVolume(val: string) {
        musicVal = val;
        musicStart.volume = +val / 100;
        musicMain.volume = +val / 100;
    }

    public start() {
        window.addEventListener("click", this.startMusicPlay);
    }

    public startMusicPlay() {
        musicStart.play();
        musicStart.addEventListener("ended", this.startMainMusic);

        window.removeEventListener("click", this.startMusicPlay);
    }

    private startMainMusic() {
        musicMain.play();
        musicMain.addEventListener("ended", this.startMainMusic);
    }

}

But for some reason, the first track plays for me and then the second one plays 1 time. I don't get looped on the second track.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2022-02-09
@fif

There is a special property:
musicMain.loop = true;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question