➤ PixiJs : Play Sound,mute,unmute using sound library and using Sprite Image ?

⇒ Here is Sprite Image for Sound On/Off (volumes.png):
⇒ Here is Html Code Sound On/Off :
<html>

<head>
    
    <script src="https://cdn.jsdelivr.net/npm/pixi.js@7.x/dist/pixi.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.2.3/howler.min.js" integrity="sha512-6+YN/9o9BWrk6wSfGxQGpt3EUK6XeHi6yeHV+TYD2GR0Sj/cggRpXr1BrAQf0as6XslxomMUxXp2vIl+fv0QRA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
   <script>
        
        const app = new PIXI.Application({
            "background": "#000", //canvas background Color
            "width":300, //canvas width
            "height":300 //canvas height
        });
        document.body.appendChild(app.view); //canvas view on your screen
        
        const container = new PIXI.Container(); //create container
        
        app.stage.addChild(container); //Add container on screen
        
        //Above see we have include sound library howler.js
        //we set sound file and loop property
        var sound = new Howl({
            src: ['sound.mp3'], //Downloaded Mp3 Music file
            loop :true
        });
        let isMute = false;
        sound.play(); //we have set default play when application loaded
        
        //load image
        PIXI.Assets.load(["volumes.png"]).then((texture) => {
            
            let volumeTexture = PIXI.utils.TextureCache["volumes.png"]; //get texture image
            //get On image from volume sprite image
            let textureOn = new PIXI.Texture(volumeTexture, new PIXI.Rectangle((volumeTexture.width / 2) * 0, 0, volumeTexture.width / 2, volumeTexture.height));
            //get On image from volume sprite image
            let textureOff = new PIXI.Texture(volumeTexture, new PIXI.Rectangle((volumeTexture.width / 2) * 1, 0, volumeTexture.width / 2, volumeTexture.height));
            const soundUnMute = PIXI.Sprite.from(textureOn);
            
    		//set mouse clickable event and set pointer
            soundUnMute.interactive = true;
            soundUnMute.cursor = 'pointer';
           
           //logic inside pinterdown event
            soundUnMute.on("pointerdown", function () {
                if (isMute == true) {
                    isMute = false;
                    sound.mute(false);
                    this.texture = textureOn;
                }
                else {
                    isMute = true;
                    sound.mute(true);
                    this.texture = textureOff;
                }
            });
            //add all that sprite in to container
            container.addChild(soundUnMute)
        });
        
        container.x = 100; //we can move container as you wish
        container.y = 100;
      
        
       
        
   </script>
</body>

</html>

⇒ Here is Output Code Sound On/Off :

Comments