gpt4 book ai didi

javascript - 在for循环中从数组中获取随机值( Angular 2)

转载 作者:行者123 更新时间:2023-12-03 04:32:22 25 4
gpt4 key购买 nike

我正在创建一个音板,当单击按钮时,它会播放随机声音。我试图通过在 for 循环内创建一个数组来获取所有 mp3 文件链接(文件名),并且当用户单击按钮时,文件名将使用 (Math.floor(Math.random)) 进行更改。

我遇到的问题是它只播放相同的声音。它不会播放随机声音。

音板.ts

    /* Loop through them, saving their title and sound file */
for(let link of links) {
let filename = link.getAttribute("href")
let rand = [filename];
this.sounds.push({
file: filename,
rand: rand
});
}

/* Plays the sound */
play(sound) {
sound.rand = sound.file[Math.floor(Math.random() * sound.file.length)];
console.log(sound.rand)
this.media = new Audio(sound.rand);
this.media.load();
this.media.play();
}

最佳答案

好像有逻辑错误。根据您的问题描述,我认为您想要类似的东西

export class Component {
soundFileNames: string[] = [];

media?: Audio;

ngOnInit() {
for (const link of links) {
const fileName = link.getAttribute("href");
soundFileNames.push(fileName);
}
}

playRandomSoundFile() {
const randomIndex = Math.floor(Math.random() * soundFileNames.length);
const randomFileName = soundFileNames[randomIndex];
console.log(randomFileName);
const audio = new Audio(randomFileName);
audio.load();
audio.play();
this.media = audio;
}
}

关于javascript - 在for循环中从数组中获取随机值( Angular 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43433575/

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