Spaces:
Runtime error
Runtime error
const express = require('express'); | |
const mm = require('music-metadata'); | |
const util = require('util'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const app = express(); | |
const PORT = process.env.PORT || 7860; | |
app.use(express.static('public')); | |
app.use('/music', express.static('music')); | |
const SUPPORTED_FORMATS = ['.mp3', '.mp4', '.wav', '.flac', '.ogg', '.opus']; // Add or remove formats as needed | |
function isSupportedFormat(filename) { | |
const ext = path.extname(filename).toLowerCase(); | |
return SUPPORTED_FORMATS.includes(ext); | |
} | |
app.get('/tracks', async (req, res) => { | |
fs.readdir('music', async (err, files) => { | |
if (err) { | |
console.error('Error reading music directory', err); | |
return res.sendStatus(500); | |
} | |
const trackDetails = []; | |
for (const file of files) { | |
if (isSupportedFormat(file)) { // Use the utility function here | |
const filePath = path.join(__dirname, 'music', file); | |
try { | |
const metadata = await mm.parseFile(filePath, { native: true }); | |
const artwork = metadata.common.picture && metadata.common.picture[0] ? `data:${metadata.common.picture[0].format};base64,${metadata.common.picture[0].data.toString('base64')}` : ''; | |
trackDetails.push({filename: file, artwork}); | |
} catch (error) { | |
console.error(`Error reading metadata for file: ${file}`, error); | |
} | |
} | |
} | |
res.json(trackDetails); | |
}); | |
}); | |
app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); |