[英]JavaScript - Play audio along with randomly generated values
I have a function that displays a random word from an array, in a non-repeated way. 我有一个函数,可以以非重复的方式显示数组中的随机单词。
I would also like to play a sound clip with each word (that sound would be the word's pronounciation). 我还想为每个单词播放一个声音剪辑(该声音将是单词的发音)。
I know how to play single sounds, and how to play random sounds from an array of sounds. 我知道如何播放单个声音,以及如何从一系列声音中播放随机声音。 But if I create an array of sounds, how can I play each one only when the corresponding word is displayed?
但是,如果我创建声音阵列,那么仅当显示相应的单词时,才能播放每个声音吗?
This is what I am working with: 这就是我正在使用的:
const p = document.getElementById("randomWord"); const origWords = ["alpha", "bravo", "charlie", "delta", "echo"]; const audioClips = ["alpha.mp3", "bravo.mp3", "charlie.mp3", "delta.mp3", "echo.mp3"]; let remainingWords = []; function randomize() { if (remainingWords.length === 0) remainingWords = origWords.slice(); const { length } = remainingWords; const [word] = remainingWords.splice(Math.floor(Math.random() * length), 1); p.textContent = word; }
<button onclick="randomize()" type="button">Random Word</button> <p id="randomWord"></p>
I would change the way you store your data. 我会改变您存储数据的方式。 Instead of
origWords
and audioClips
you could use an Array of Objects: 除了使用
origWords
和audioClips
还可以使用对象数组:
const myWords = [
{
text: "alpha",
audio: "alpha.mp3"
},
{
text: "bravo",
audio: "bravo.mp3"
},
...
]
Then in your function after you get the random index just acces the .text
or .audio
keys 然后在您的函数中,获得随机索引后,只需访问
.text
或.audio
键
Edit: Snippet 编辑:片段
const p = document.getElementById("randomWord"); const myWords = [ { text: "alpha", audio: "alpha.mp3" }, { text: "bravo", audio: "bravo.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; // your audio code here like audio.play(word.audio); }
<button onclick="randomize()" type="button">Random Word</button> <p id="randomWord"></p>
I would use an hashmap, for example: 我将使用一个哈希图,例如:
const origWords = {"alpha":"alpha.mp3", "bravo":"bravo.mp3", "charlie":"charlie.mp3", "delta":"delta.mp3", "echo":"echo.mp3"};
...
randomIndex = randomize();
key = Object.keys(origWords)[randomIndex];
p.textContent = key;
playSound(origWords[key]);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.