如何使用JavaScript处理一个文件夹中的多个值?

如何使用JavaScript处理一个文件夹中的多个值?,javascript,html,html5-audio,Javascript,Html,Html5 Audio,我想在我的页面上添加随机音乐播放器 并找到了随机音乐播放器的源代码。但它只有两种音乐 如果我在“音频”文件夹中有许多超过100个的音乐文件,有没有一些处理许多音乐文件的技巧 这是我的JavaScirpt代码 var lastSong = null; var selection = null; var playlist = ["audio/Boy with luv.mp3", "audio/Mikrokosmos.mp3"]; // List of Songs var player = doc

我想在我的页面上添加随机音乐播放器
并找到了随机音乐播放器的源代码。但它只有两种音乐

如果我在“音频”文件夹中有许多超过100个的音乐文件,有没有一些处理许多音乐文件的技巧

这是我的JavaScirpt代码

var lastSong = null;
var selection = null;
var playlist = ["audio/Boy with luv.mp3", "audio/Mikrokosmos.mp3"]; // List of Songs

var player = document.getElementById("audioplayer"); // Get Audio Element
player.autoplay = true;
player.addEventListener("ended", selectRandom); // Run function when song ends

function selectRandom() {
  while (selection == lastSong) {
    // Repeat until different song is selected
    selection = Math.floor(Math.random() * playlist.length);
  }
  lastSong = selection; // Remember last song
  player.src = playlist[selection]; // Tell HTML the location of the new Song
}

selectRandom(); // Select initial song
player.play(); // Start Song
上述代码

var playlist = ["audio/Boy with luv.mp3", "audio/Mikrokosmos.mp3"];
如果播放列表中有许多音乐文件,我想使用like for function等添加音乐文件。

您可以这样做

const fs = require('fs'); // file handling module
const files = fs.readdirSync('.'); // use to read all avaliable file in the current directory
const extname = '.mp3'; // audio file extension
const playlist = files.filter(file => file.endsWith(extname)); // filter out all the files which have `.mp3` extension 
将这些行添加到下一行的上方

var lastSong = null;
并删除您声明的
playlist
,因为我们现在有一个来自此
const playlist=files.filter(file=>file.endsWith(extname))

注意:确保您的代码和mp3文件位于同一目录中