3

I have the below code where the function clickSound just plays a simple button click sound audio without any loop and the function loopSound plays music in a loop.However I am unable to play both at the same time i.e. (in case the music is playing and I want to click a button for example).

How can I implement that using the same instance or will I have to create two instances and change my code from being a singleton?

Note: I am using the **audioplayers ** package

import 'package:audioplayers/audioplayers.dart';
import 'package:biblequiz/services/preferences.dart';

class AudioService {
  AudioPlayer player = AudioPlayer();

  static final AudioService instance = AudioService._();

  AudioService._() {
    this.player.setVolume(1.0);
  }

  void clickSound() async {
    await player.play(AssetSource('sounds/click.mp3'));      
  }

  void loopSound() async {
      player.setReleaseMode(ReleaseMode.loop);
      await player.play(AssetSource('sounds/music.wav'));
  }

  void stopLoop() async {
    await player.stop();
  }
}
Teknoville
  • 459
  • 1
  • 7
  • 18
  • Do you want to play the song and play on loop with a single click ? or after playing the song, want to set on loop ? – Sapinder Singh Nov 11 '22 at 15:39
  • @SapinderSingh The song will be playing as background music as its a game app.But I also want to play a click sound on clicking a button as the user navigates the game.Currently the music looping is stopped if I play the click sound. – Teknoville Nov 11 '22 at 16:06

1 Answers1

0

Just create a new instance of AudioPlayer for each new sound you want to play. audioplayers getting started

Also, your singleton is not complete dart singleton. What about just static methods? KISS and YAGNI.

  import 'package:audioplayers/audioplayers.dart';

class AudioService {
  static AudioPlayer loopPlayer = AudioPlayer();
  static void loopSound(String src, double volume) async {
    loopPlayer.setVolume(volume);
    loopPlayer.setReleaseMode(ReleaseMode.loop);
    await loopPlayer.play(AssetSource(src));
  }

  static void stopLoop() async {
    await loopPlayer.stop();
  }

  static void clickSound(String src, double volume) async {
    AudioPlayer player = AudioPlayer();
    player.setVolume(volume);
    await player.play(AssetSource(src));
  }
}
Yuriy N.
  • 4,936
  • 2
  • 38
  • 31