import 'package:audioplayers/audioplayers.dart'; import 'package:wow_english/common/extension/string_extension.dart'; enum AudioPlayerUtilType { welcomeToWow('welcome_to_wow'), classTime('class_time'), gameTime('game_time'), musicTime('music_time'), readingTime('reading_time'), videoTime('video_time'), quizTime('quiz_time'), countWithMe('count_with_me_instrumental'), inMyTummy('in_my_tummy_instrumental'), touch('touch_instrumental'); const AudioPlayerUtilType(this.path); final String path; } class AudioPlayerUtil { static AudioPlayerUtil? _instance; late AudioPlayer audioPlayer; late AudioPlayerUtilType currentType; // 私有构造函数 AudioPlayerUtil._internal() { audioPlayer = AudioPlayer(); audioPlayer.onPlayerStateChanged.listen((event) async { if (event == PlayerState.completed) { // 播放结束再次播放 if (currentType == AudioPlayerUtilType.inMyTummy) { AudioPlayerUtil.getInstance() .playAudio(AudioPlayerUtilType.inMyTummy); } if (currentType == AudioPlayerUtilType.countWithMe) { AudioPlayerUtil.getInstance() .playAudio(AudioPlayerUtilType.countWithMe); } if (currentType == AudioPlayerUtilType.welcomeToWow) { AudioPlayerUtil.getInstance().playAudio(AudioPlayerUtilType.touch); } if (currentType == AudioPlayerUtilType.touch) { AudioPlayerUtil.getInstance().playAudio(AudioPlayerUtilType.touch); } } }); } static AudioPlayerUtil getInstance() { _instance ??= AudioPlayerUtil._internal(); return _instance!; } // 播放音频 Future playAudio(AudioPlayerUtilType type) async { currentType = type; String path = type.path; await audioPlayer.play(AssetSource(path.assetMp3), volume: 0.5); await audioPlayer.onPlayerComplete.first; } // stop void stop() { audioPlayer.stop(); } // pause void pause() { if (audioPlayer.state == PlayerState.playing) { audioPlayer.pause(); } } // resume void resume() { if (audioPlayer.state == PlayerState.paused) { audioPlayer.resume(); } } }