我有一个函数,可以以不重复的方式显示对象数组中的随机单词。
我的目标是让它播放每个单词的声音剪辑(该声音将是该单词的发音)。
但是,由于某种原因,我在任何浏览器中都听不到任何声音,也没有显示任何错误消息。可能是什么原因?
这就是我正在处理的内容:
const p = document.getElementById("randomWord");
const myWords = [
{
text: "alpha",
audio: "alpha.mp3"
},
{
text: "bravo",
audio: "bravo.mp3"
},
{
text: "charlie",
audio: "charlie.mp3"
},
{
text: "delta",
audio: "delta.mp3"
},
{
text: "echo",
audio: "echo.mp3"
}
];
let remainingWords = [];
function randomize() {
if (remainingWords.length === 0) remainingWords = myWords.slice();
let length = remainingWords.length;
let randomIndex = Math.floor(Math.random() * length);
const word = remainingWords[randomIndex];
remainingWords.splice(randomIndex, 1);
console.log(word);
console.dir(p);
p.textContent = word.text;
document.getElementById("soundClip").play(word.audio);
}
<audio id="soundClip">Your browser does not support the audio element.</audio>
<button onclick="randomize()" type="button">Random Word</button>
<p id="randomWord"></p>
最佳答案
HTMLMediaElement.play()
function不接受参数,而您正尝试传入一个参数。
未使用的参数在 JavaScript 中并不是 fatal error ;它们只是没有被使用,所以出于所有意图和目的,您只是调用 .play()
.
自 <audio>
元素没有与之关联的源,没有任何内容播放。
尝试
const audioElement = document.getElementById("soundClip");
audioElement.src = word.audio;
audioElement.play();
相反。
关于JavaScript - 声音不随随机值一起播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907550/