扑击与 dart :如何在App中同时播放多个声音?

soat7uwm  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(138)

我有下面的代码,其中函数clickSound只是播放一个简单的按钮点击声音音频,没有任何循环,函数loopSound循环播放音乐。但是我无法同时播放两者,即(例如,如果音乐正在播放,我想点击按钮)。
我如何使用同一个示例来实现它呢?或者我必须创建两个示例并将我的代码从单例模式更改为单例模式?
注意:我使用的是audioplayer

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();
  }
}
9udxz4iz

9udxz4iz1#

只需为您想要播放的每个新声音创建AudioPlayer的新示例。audioplayers getting started
另外,你的单例并不是完整的dart singleton。如果只是静态方法呢?KISSYAGNI

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));
  }
}

相关问题