基于umi的开发模板

voice_play.ts 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import request from '../request';
  2. import { AUDIO_BASE_URL } from '@/api_config';
  3. let audio_url = "";
  4. export function* getAudioSrc({ word, language = "zh-CN", gender = "FEMALE" }: any): any {
  5. if (audio_url === "") {
  6. const req_data = yield request(AUDIO_BASE_URL);
  7. if (!req_data || !req_data.audio_base_url) {
  8. return false;
  9. }
  10. audio_url = req_data.audio_base_url;
  11. }
  12. const word_src = `${audio_url}?text=${word}&languageCode=${language}&gender=${gender}`;
  13. return word_src;
  14. }
  15. class AudioPlayer {
  16. public AudioInstance: HTMLAudioElement;
  17. public play_list: Array<string>;
  18. public play_word: Array<string>;
  19. public play_index: number;
  20. public is_pause: boolean;
  21. constructor() {
  22. this.AudioInstance = new Audio();
  23. this.play_list = [];
  24. this.play_word = [];
  25. this.play_index = 0;
  26. this.is_pause = false;
  27. this.AudioInstance.addEventListener("ended", () => {
  28. if (this.play_list[this.play_index + 1]) {
  29. // 播放下一个音频
  30. this.play_index += 1;
  31. this.playAudio();
  32. }
  33. });
  34. }
  35. playAudio = () => {
  36. if (this.is_pause) {
  37. this.is_pause = false;
  38. this.AudioInstance.src = this.play_list[this.play_index];
  39. this.AudioInstance.play();
  40. return;
  41. }
  42. this.AudioInstance.src = this.play_list[this.play_index];
  43. this.AudioInstance.load();
  44. this.AudioInstance.play();
  45. return;
  46. };
  47. addAudio = (play_src: string, play_word: string) => {
  48. this.play_word.push(play_word);
  49. this.play_list.push(play_src);
  50. };
  51. pauseAudio = () => {
  52. this.is_pause = true;
  53. this.AudioInstance.pause();
  54. };
  55. preloadAudio = () => {
  56. this.AudioInstance.src = "";
  57. this.AudioInstance.load();
  58. };
  59. clearAudioInstance = () => {
  60. this.is_pause = true;
  61. this.AudioInstance.pause();
  62. this.play_list = [];
  63. this.play_word = [];
  64. this.play_index = 0;
  65. };
  66. }
  67. export const ExportAudioPlayer = new AudioPlayer();
  68. export function subscriptAudioCanPlay(action: any) {
  69. if (typeof window !== "undefined") {
  70. ExportAudioPlayer.AudioInstance.addEventListener("canplaythrough", () => {
  71. action({
  72. type: "can_play"
  73. });
  74. });
  75. ExportAudioPlayer.AudioInstance.addEventListener("error", (err: any) => {
  76. action({
  77. type: "load_fail",
  78. });
  79. ExportAudioPlayer.clearAudioInstance();
  80. });
  81. }
  82. }
  83. export default {
  84. ExportAudioPlayer,
  85. getAudioSrc,
  86. subscriptAudioCanPlay,
  87. }