我正在开发一个简单的 Vue 应用程序,它播放两个音频文件并要求用户确定它们之间的音频间隔。我目前无法播放任何音频文件。每当我的 playNote()
函数被调用时,Chrome 就会抛出错误 Uncaught (in Promise) DOMException: Failed to load because no 支持的源被发现。
我尝试更改音频文件类型,以防正在读取的文件出现问题。我尝试更改音频文件所在的位置,以防 Vue 访问该文件时遇到问题(当前该文件位于与 Vue 组件相同的文件夹中,用于故障排除)。这些都没有解决我遇到的错误。
我尝试在 Firefox 中打开 Vue 应用程序,并在调用 playNote()
时收到类似的字符串错误:
不支持“text/html”的“Content-Type”。媒体资源加载失败。
NotSupportedError:src 属性指示的媒体资源或分配的媒体提供程序对象不合适。
无法播放媒体。所请求的格式没有解码器:text/html
我已将代码精简为仅播放按钮和相关功能,希望我的其他功能之一会意外干扰,但即使使用下面的内容,我也会遇到相同的错误:
<template>
<div class="hello">
<h1>Ear Training</h1>
<button v-on:click='playNote'>Play</button>
</div>
</template>
<script>
export default {
name: 'Intervals',
data: function() {
return {
middleC: 'middleC.aiff',
}
},
methods: {
// Selects a note
getNote: function() {
return this.middleC;
},
// Plays a note, selected via getNote()
playNote: function() {
let note = new Audio(this.getNote);
note.play();
}
},
}
</script>
任何帮助或指导都将非常棒 - 提前谢谢您!
更新:
我根据您的建议更新了代码,但仍然无法播放音频。
<template>
<div class="hello">
<h1>Ear Training</h1>
<button v-on:click='playNote'>Play</button>
</div>
</template>
<script>
const someSound = require("../assets/audio/middleC.mp3");
export default {
name: "Intervals",
data: () => ({
someSound
}),
methods: {
playNote() {
console.log('calling playNote()');
let note = new Audio(this.someSound);
note.addEventListener("canplaythrough", () => {
console.log('event listener called');
note.play();
});
}
}
};
</script>
当我点击页面上的播放按钮时,控制台会读取calling playNote()
,这意味着该函数正在被调用。但是,调用的事件监听器
永远不会被记录,这意味着事件监听器永远不会执行操作。
最佳答案
尝试以这种方式导入音频
const sound = require("@/assets/hey.mp3");
我将采用相同的模板,因此我将更新您的导出默认对象:
<script>
const someSound = require("@/assets/hey.mp3"); // require the sound
export default {
name: "playASound",
data: () => ({
// you can access to the sound with this.someSound
// same as someSound: someSound
someSound
}),
methods: {
// Selects a note
// This method doesn't add value to the component, you can use
// this.someSound directly
getNote() {
return this.someSound;
},
playNote() {
// Plays a note, selected via getNote()
//let note = new Audio(this.getNote()); // or
let note = new Audio(this.someSound);
// note.play(); // new Audio will load asynchronously the audio
// so instead of play directly after create note, you can listen for
// a event and wait for it to know that the sound was loaded and can be
// played
// listen for the canplaythrough event
note.addEventListener("canplaythrough", () => {
/* the audio is now playable; play it if permissions allow */
note.play(); // the audio now can be played
});
}
}
};
</script>
您可以阅读有关音频事件的更多信息 here
如果使用我的解决方案有不清楚的地方或者您的代码无法正常工作,请告诉我。
关于javascript - 无法在 Vue Web 应用程序中播放音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62524111/