1

My app is playing some audios depending on various triggers. I want the user to be able to stop the sound when he decides it.

this is what I did, based on this post:

  audioPlayer(sound){
      const audioGetReady = new Audio("...mp3")
      const audioTenSec = new Audio("...mp3");
      const audioNext = new AudioAudio("...mp3");
      const audioRest = new AudioAudio("...mp3")
      const audioCongrats = new AudioAudio("...mp3")

      if(sound == 'getReady'){
        audioGetReady.play()
      }
      if(sound == 'tenSeconds'){
        audioTenSec.play()
      }
      if(sound == 'next'){
        audioNext.play()
      }
      if(sound == 'rest'){
        audioRest.play()
      }
      if(sound == 'congrats'){
        audioCongrats.play()
      }
      if(sound == 'stop'){
        audioGetReady.pause();
        audioGetReady.currentTime = 0;
        audioTenSec.pause();
        audioTenSec.currentTime = 0;
        audioNext.pause();
        audioNext.currentTime = 0;
        audioRest.pause();
        audioRest.currentTime = 0;
        audioCongrats.pause();
        audioCongrats.currentTime = 0;
      }
    }

It doesn't work, I also tried to use ".muted = true;" as shown here

Doge
  • 93
  • 3
  • 11

1 Answers1

2

I think your code should be like below. In your code, every time you call audioPlayer function, new Audio object is created, which means the audio you start and pause are different.

  audioGetReady = new Audio("...mp3");
  audioTenSec = new Audio("...mp3");
  audioNext = new AudioAudio("...mp3");
  audioRest = new AudioAudio("...mp3");
  audioCongrats = new AudioAudio("...mp3");

  audioPlayer(sound){
    if(sound == 'getReady'){
      this.audioGetReady.play()
    }
    if(sound == 'tenSeconds'){
      this.audioTenSec.play()
    }
    if(sound == 'next'){
      this.audioNext.play()
    }
    if(sound == 'rest'){
      this.audioRest.play()
    }
    if(sound == 'congrats'){
      this.audioCongrats.play()
    }
    if(sound == 'stop'){
      this.audioGetReady.pause();
      this.audioGetReady.currentTime = 0;
      this.audioTenSec.pause();
      this.audioTenSec.currentTime = 0;
      this.audioNext.pause();
      this.audioNext.currentTime = 0;
      this.audioRest.pause();
      this.audioRest.currentTime = 0;
      this.audioCongrats.pause();
      this.audioCongrats.currentTime = 0;
    }
  }
ZeroCho
  • 1,358
  • 10
  • 23