修改播放声音通用组件

This commit is contained in:
田岩
2025-08-27 21:04:34 +08:00
parent 42b22ebc95
commit b68783956e
13 changed files with 221 additions and 149 deletions
+8 -7
View File
@@ -68,8 +68,10 @@ export const useAudioStore = defineStore('audioStore', {
// 音频可以播放时触发(此时通常能获取到时长)
this.audioInstance.onCanplay(() => {
// 尝试获取时长(部分环境需要延迟一点)
console.log('尝试获取时长(部分环境需要延迟一点)');
setTimeout(() => {
const duration = this.audioInstance.duration || 0;
console.log('尝试获duration', duration);
if (duration > 0) {
this.duration = duration;
this.isLoaded = true;
@@ -114,12 +116,11 @@ export const useAudioStore = defineStore('audioStore', {
try {
// 先停止当前播放并清空旧地址
this.audioInstance.stop();
this.audioInstance.src = '';
// this.audioInstance.stop();
// this.audioInstance.src = '';
// 设置新地址并加载(不自动播放)
this.audioInstance.src = src;
this.audioInstance.load(); // 手动触发加载
// this.audioInstance.load(); // 手动触发加载
} catch (err) {
this.isLoading = false;
this.errorMsg = `设置音频失败: ${err.message}`;
@@ -134,11 +135,12 @@ export const useAudioStore = defineStore('audioStore', {
}
// 已在播放则暂停
console.log('已在播放则暂停', this.isPlaying);
if (this.isPlaying) {
this.pauseAudio();
return;
}
console.log('未加载完成则等待加载', this.isLoaded);
// 未加载完成则等待加载
if (!this.isLoaded) {
this.isLoading = true;
@@ -175,7 +177,7 @@ export const useAudioStore = defineStore('audioStore', {
resetAudioState() {
this.isPlaying = false;
this.isLoading = false;
this.currentSrc = '';
// this.currentSrc = '';
// 清空地址避免残留
if (this.audioInstance) {
this.audioInstance.src = '';
@@ -225,7 +227,6 @@ export const useAudioStore = defineStore('audioStore', {
this.callbacks.onLoaded = callback;
}
},
}
});