audio.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { rejects } from "assert";
  2. import { Howl, HowlCallback } from "howler";
  3. import { resolve } from "path";
  4. import { ref, watch, ComputedRef } from "vue";
  5. import { useStore } from "vuex";
  6. export function useAudio() {
  7. const store = useStore()
  8. const token = "Bearer " + store.getters.getToken;
  9. let sound: Howl = store.state.lightAudio
  10. let pauseAudio = () => {
  11. sound && sound.pause();
  12. }
  13. let stopAudio = () => {
  14. sound && sound.stop()
  15. }
  16. let playAudio = (url: string) => {
  17. stopAudio()
  18. sound = new Howl({
  19. src: url,
  20. html5: true,
  21. xhr: {
  22. method: 'GET',
  23. headers: {
  24. Authorization: 'Bearer:' + token,
  25. },
  26. withCredentials: true,
  27. }
  28. });
  29. return new Promise((resolve, reject) => {
  30. sound.once("load", function () {
  31. let id = sound.play();
  32. if (id) {
  33. resolve(id)
  34. }
  35. else {
  36. reject("id错误")
  37. }
  38. });
  39. })
  40. }
  41. let audioOnce = (event: string, callback: HowlCallback) => {
  42. sound.once(event, callback)
  43. }
  44. let audioOn = (event: string, callback: HowlCallback) => {
  45. sound.on(event, callback)
  46. }
  47. let playMulAudio = (urls: string[]) => {
  48. pauseAudio()
  49. sound = new Howl({
  50. src: urls
  51. });
  52. }
  53. let durationAudio = (id?: number) => {
  54. return sound && sound.duration(id)
  55. }
  56. return {
  57. playAudio,
  58. audioOnce,
  59. audioOn,
  60. playMulAudio,
  61. pauseAudio,
  62. stopAudio,
  63. durationAudio
  64. }
  65. }