gpt4 book ai didi

JavaScript - 播放音频以及随机生成的值

转载 作者:行者123 更新时间:2023-12-01 01:35:02 25 4
gpt4 key购买 nike

我有一个函数,可以以不重复的方式显示数组中的随机单词。

我还想为每个单词播放一个声音剪辑(该声音将是该单词的发音)。

我知道如何播放单个声音,以及如何播放一组声音中的随机声音。但是如果我创建一组声音,如何仅在显示相应的单词时播放每个声音?

这就是我正在处理的内容:

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>

最佳答案

我会改变您存储数据的方式。您可以使用对象数组来代替 origWordsaudioClips:

const myWords = [
{
text: "alpha",
audio: "alpha.mp3"
},
{
text: "bravo",
audio: "bravo.mp3"
},
...
]

然后在您的函数中获得随机索引后只需访问 .text.audio

编辑:片段

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>

关于JavaScript - 播放音频以及随机生成的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com