12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import {nextTick, ref} from "vue";
- import { debounce } from "@/utils/common";
- export function useAudio() {
- const innerAudioContext = ref(null);
- const options = ref(null);
- function createAudio(audioUrl) {
- const innerAudioContext = uni.createInnerAudioContext();
- innerAudioContext.autoplay = false;
- innerAudioContext.src = audioUrl;
- innerAudioContext.onPlay(() => {
- // 播放
- uni.$emit('yy-audio-playing', options);
- });
- innerAudioContext.onError((res) => {
- uni.$emit('yy-audio-error')
- });
- innerAudioContext.onEnded(() => {
- // 播放结束
- uni.$emit('yy-audio-end',options)
- })
- return innerAudioContext;
- }
- function changeSource(url) {
- innerAudioContext.src= url;
- innerAudioContext.currentTime = 0;
- }
-
- const debuncePlay = debounce((myOption) => {
- innerAudioContext.value = createAudio(myOption.url);
- innerAudioContext.value.play()
- },50)
-
- function handlePlay(data) {
- if (innerAudioContext.value) {
- innerAudioContext.value.stop();
- innerAudioContext.value.destroy();
- innerAudioContext.value = null;
- uni.$emit('destory-stop')
- }
- options.value = data;
- debuncePlay(data);
- }
-
- function handleStop() {
- // console.log('stop')
- if (innerAudioContext.value) {
- innerAudioContext.value.destroy();
- innerAudioContext.value = null;
- uni.$emit('destory-stop')
- }
- }
- // 离开当前页面 停止播放
- uni.$on('back-outpage',() => {
- handleStop();
- })
- // 播放过程中点击同一个视频触发终止
- uni.$on('repeat-play-to-stop',() => {
- handleStop();
- })
- // 试题切换停止播放
- uni.$on('swiper-change',() => {
- handleStop();
- })
- // 解析关闭 停止播放
- uni.$on('question-jiexi-close',() => {
- handleStop();
- })
- // 交卷 停止播放
- uni.$on('unitTest-submit', () => {
- handleStop();
- })
-
- return {
- options,
- handlePlay,
- handleStop,
- innerAudioContext
- }
- }
|