一、前言
一般情况下,audioPlayer最好设置成单例模式,这样在跨页面操作时会更好的使用。确保所有对象都访问一个实例。
二、引用
audioplayers
功能:控制mp3文件播放。
地址:https://pub.dev/packages/audioplayers
使用文章:https://blog.csdn.net/qq_38779672/article/details/122383327
event_bus
功能:实现广播功能。
地址:https://pub.dev/packages/event_bus
使用文章:https://blog.csdn.net/qq_38779672/article/details/122167761
三、运用
1 声明
import 'package:audioplayers/audioplayers.dart';
class AudioPlayUtil{
  late AudioPlayer audioPlayer;
  // static _instance,_instance会在编译期被初始化,保证了只被创建一次
  static final AudioPlayUtil _instance = AudioPlayUtil._internal();
  //提供了一个工厂方法来获取该类的实例
  factory AudioPlayUtil(){
    return _instance;
  }
  // 通过私有方法_internal()隐藏了构造方法,防止被误创建
  AudioPlayUtil._internal(){
    audioPlayer = AudioPlayer();
  }
  /// 播放
  Future play(String videoPath) async {
    int result = await audioPlayer.setUrl(videoPath);
    await audioPlayer.resume();
    callback();
    return result;
  }
  /// 继续播放
  Future continuePlay() async {
    int result = await audioPlayer.resume();
    return result;
  }
  /// 暂停
  Future pause() async {
    int result = await audioPlayer.pause();
    return result;
  }
  /// 拖动播放
  Future seekPlay(Duration duration) async {
    int result = await audioPlayer.seek(duration);
    return result;
  }
  /// 回调
  Future callback() async {
    audioPlayer.onAudioPositionChanged.listen((event) {
      /// 广播部分,event为Duration类
    });
  }
}
 
2 使用
await AudioPlayUtil().play(videoPath);
await AudioPlayUtil().pause();
await AudioPlayUtil().seekPlay(duration);
...










