Search code examples
javascriptexpresssocket.ioreplit

How can I play a mp3 file in a Nodejs Replit?


I have a mp3 file and I would like to play it when a button is pressed. But I belive I am not serving the file to the server correctly. Here is the code on Replit.com:

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env['port'];
const admin = require('firebase-admin');
const express = require("express");
const path = require("path");

admin.initializeApp();

const db = admin.firestore();

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index/index.html');
});
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index/script.js');
});
app.get('/', (req, res) => {
    res.sendFile(__dirname + './index/ding.mp3');
});

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        if (msg === "ping") {
            io.emit('chat message', "pong");
        }
        io.emit('chat message', msg);
    });
    socket.on('serverLog', (m) => {
        console.log(m);
    });
    socket.on('loggedInWithName', (name) => {
        console.log('User Connected. Username: ' + name);
    });

});

http.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}`);
});

Replit.com


Solution

  • I've tested the repl, and it works. Check your volume settings.

    Tip. If you don't want to repeat res.sendFile for each static file, I recommend to use this notation:

    app.use('/static', express.static(path.join(__dirname, 'public')))