Hibok
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

100 rader
2.4 KiB

  1. import 'package:audioplayer/audioplayer.dart';
  2. import 'package:chat/data/constants.dart';
  3. import 'package:chat/utils/sp_utils.dart';
  4. import 'package:flutter/widgets.dart';
  5. class SoundUtils {
  6. // 工厂模式
  7. factory SoundUtils() => _getInstance();
  8. static SoundUtils get instance => _getInstance();
  9. static SoundUtils _instance;
  10. String curSoundUrl;
  11. Map<String, bool> soundStateMap = {};
  12. SoundUtils._internal() {
  13. // 初始化
  14. audioPlugin = new AudioPlayer();
  15. stateStream = audioPlugin.onPlayerStateChanged;
  16. }
  17. AudioPlayer audioPlugin;
  18. // AudioCache audioCache = AudioCache();
  19. Stream<AudioPlayerState> stateStream;
  20. bool isPlaying(url) {
  21. return soundStateMap[url] ?? false;
  22. }
  23. static SoundUtils _getInstance() {
  24. if (_instance == null) {
  25. _instance = new SoundUtils._internal();
  26. }
  27. return _instance;
  28. }
  29. initPlayMode() async {
  30. bool playMode = await SPUtils.getBool(Constants.SOUND_PLAY_MODE);
  31. if (playMode != null && playMode) {
  32. setReceiver(true);
  33. } else {
  34. setReceiver(false);
  35. }
  36. }
  37. savePlayModeConfig(bool playMode) async {
  38. await SPUtils.saveBool(Constants.SOUND_PLAY_MODE, playMode);
  39. setReceiver(playMode);
  40. }
  41. ///设置听筒true 设置外放false
  42. setReceiver(bool setReceiver) async {
  43. await audioPlugin.setReceiver(setReceiver);
  44. }
  45. play(url,
  46. {bool isLocal = true,
  47. VoidCallback onPlayed,
  48. VoidCallback complete}) async {
  49. if (curSoundUrl != null && curSoundUrl != url) {
  50. print('不是同一个音频文件');
  51. await stop();
  52. }
  53. print('播放url:$url');
  54. await audioPlugin.play(url, isLocal: isLocal);
  55. curSoundUrl = url;
  56. stateStream.listen((state) {
  57. if (state == AudioPlayerState.PLAYING) {
  58. soundStateMap[curSoundUrl] = true;
  59. if (onPlayed != null) {
  60. onPlayed();
  61. }
  62. } else {
  63. soundStateMap[curSoundUrl] = false;
  64. if (complete != null) {
  65. complete();
  66. }
  67. }
  68. });
  69. }
  70. pause() async {
  71. print('暂停播放');
  72. if (curSoundUrl != null) {
  73. soundStateMap[curSoundUrl] = false;
  74. await audioPlugin.pause();
  75. }
  76. }
  77. stop() async {
  78. if (curSoundUrl != null) {
  79. soundStateMap[curSoundUrl] = false;
  80. await audioPlugin.stop();
  81. }
  82. }
  83. }