123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import request from '../request';
- import { AUDIO_BASE_URL } from '@/api_config';
- let audio_url = "";
-
- export function* getAudioSrc({ word, language = "zh-CN", gender = "FEMALE" }: any): any {
- if (audio_url === "") {
- const req_data = yield request(AUDIO_BASE_URL);
- if (!req_data || !req_data.audio_base_url) {
- return false;
- }
- audio_url = req_data.audio_base_url;
- }
- const word_src = `${audio_url}?text=${word}&languageCode=${language}&gender=${gender}`;
- return word_src;
- }
-
- class AudioPlayer {
- public AudioInstance: HTMLAudioElement;
- public play_list: Array<string>;
- public play_word: Array<string>;
- public play_index: number;
- public is_pause: boolean;
-
- constructor() {
- this.AudioInstance = new Audio();
- this.play_list = [];
- this.play_word = [];
- this.play_index = 0;
- this.is_pause = false;
- this.AudioInstance.addEventListener("ended", () => {
- if (this.play_list[this.play_index + 1]) {
- // 播放下一个音频
- this.play_index += 1;
- this.playAudio();
- }
- });
- }
-
- playAudio = () => {
- if (this.is_pause) {
- this.is_pause = false;
- this.AudioInstance.src = this.play_list[this.play_index];
- this.AudioInstance.play();
- return;
- }
- this.AudioInstance.src = this.play_list[this.play_index];
- this.AudioInstance.load();
- this.AudioInstance.play();
- return;
- };
-
- addAudio = (play_src: string, play_word: string) => {
- this.play_word.push(play_word);
- this.play_list.push(play_src);
- };
-
- pauseAudio = () => {
- this.is_pause = true;
- this.AudioInstance.pause();
- };
-
- preloadAudio = () => {
- this.AudioInstance.src = "";
- this.AudioInstance.load();
- };
-
- clearAudioInstance = () => {
- this.is_pause = true;
- this.AudioInstance.pause();
- this.play_list = [];
- this.play_word = [];
- this.play_index = 0;
- };
-
- }
-
- export const ExportAudioPlayer = new AudioPlayer();
-
- export function subscriptAudioCanPlay(action: any) {
- if (typeof window !== "undefined") {
- ExportAudioPlayer.AudioInstance.addEventListener("canplaythrough", () => {
- action({
- type: "can_play"
- });
- });
- ExportAudioPlayer.AudioInstance.addEventListener("error", (err: any) => {
- action({
- type: "load_fail",
- });
- ExportAudioPlayer.clearAudioInstance();
- });
- }
- }
-
- export default {
- ExportAudioPlayer,
- getAudioSrc,
- subscriptAudioCanPlay,
- }
|