Toggling Audio and Icon with Button Press in Flutter

50 Views Asked by At

I am a beginner with flutter and can't get the audio to stop playing using the same button that initialises it. The audio is meant to start playing with the first press and toggles on/off with the same button after. The icon is also meant to toggle between volume_off and volume_up.

I previously tried using a boolean variable which would change value with every press that switches between the music mp3 file and a silent mp3 file along with the icons.

Container(
                  alignment: Alignment.topLeft,
                    child: IconButton(
                     icon: Icon(Icons.volume_up),
                      color: Colors.white,
                        splashColor: Colors.black,
                        iconSize: 50.0,
                      onPressed: () {
                       final player=AudioCache();
                       player.play('seamusic.mp3');
                       },
                    ),
                ),
1

There are 1 best solutions below

0
Furkan Topaloglu On
      bool playing = false;
      AudioCache audioCache = AudioCache();

You can achieve the desired result with a boolean variable. Try the code below.

Container(
    alignment: Alignment.topLeft,
    child: IconButton(
      icon: Icon(playing ? Icons.volume_up : Icons.volume_off),
      color: Colors.white,
      splashColor: Colors.black,
      iconSize: 50.0,
      onPressed: () {
        if (playing) {
          // If music is currently playing, stop it.
          setState(() {
            playing = false;
          });
          // Stop the music.
           audioCache.stop();
        } else {
          // If music is not playing, start it.
          setState(() {
            playing = true;
          });
          // Start the music.
         audioCache.play('seamusic.mp3');
        }
      },
    ),
  ),

The above code restarts the music from the beginning every time. If you want to resume from where it left off, you can use the code snippet below.

Container(
    alignment: Alignment.topLeft,
    child: IconButton(
      icon: Icon(playing ? Icons.volume_up : Icons.volume_off),
      color: Colors.white,
      splashColor: Colors.black,
      iconSize: 50.0,
      onPressed: () {
        if (playing) {
          // If music is currently playing, pause it.
          setState(() {
            playing = false;
          });
          audioCache.fixedPlayer?.pause();
        } else {
          // If music is not playing, resume from where it left off.
          setState(() {
            playing = true;
          });
          audioCache.fixedPlayer?.resume();
          // If it hasn't been played before, start from the beginning.
          if (audioCache.fixedPlayer == null || !audioCache.fixedPlayer!.isPlaying) {
            audioCache.play('seamusic.mp3');
          }
        }
      },
    ),
  ),

You should visit here for more information.