我想从我的React App的众多歌曲中选择随机的背景歌曲

时间:2019-02-09 17:18:26

标签: reactjs

每次用户加载应用程序时,都会播放另一首歌曲。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您需要具有歌曲列表列表;

const songsCollections = ['http://www.music.helsinki.fi/tmt/opetus/uusmedia/esim/a2002011001-e02.wav', 'http://www.noiseaddicts.com/samples_1w72b820/2563.mp3', 'http://www.noiseaddicts.com/samples_1w72b820/2558.mp3'];

const getRandomFromRange = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min);
};

const randomSongIndex = getRandomFromRange(0, songsCollections.length);

console.log('Random song index is ', randomSongIndex)

const randomSong = songsCollections[randomSongIndex];
new Audio(randomSong).play()

您需要拥有一组歌曲,然后使用随机函数选择随机歌曲并使用Javascript的Audio方法play()选择歌曲。