Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Audio from client when message is recieved from socket.io - node.js

I've searched for a while for a solution to this problem, but haven't found much.

My goal is to recieve a message from a udp client, which the server recieves and forwards to a web client, which plays an audio clip each time a message is recieved. However, for some reason the audio will not play. If I open the page straight from my directory, the audio can be played, but if I try and access it through localhost it fails to load. Does anyone know of a solution?

Here is the client side javascript.

var mySound = new Audio('/public/audio/Bloom.mp3');
mySound.load();
var socket = io.connect('http://localhost');
socket.on('message', function(data){
    console.log(data);
    $('#content').text(data);
    mySound.play();
    //document.getElementById('audiotag1').play();
});

This page is served by server.js, a node.js file using socket.io and express. I don't receive any errors from my console.log. Here is the server.js

var app = require('express')()
    , server = require('http').Server(app)
    , io =require('socket.io')(server)
    , dgram = require('dgram');

var httpPort = 1234;
var udpPort = 5000;

server.listen(httpPort);

app.use(server.express.static( __dirname + '/public'));

app.get('/', function(request, response){
    var ipAddress = request.socket.remoteAddress;
    console.log("New express connection from: " + ipAddress);
    response.sendfile(__dirname + '/public/index.html');
});

var udpSocket = dgram.createSocket('udp4', function(msgBuffer){
    var jsonMessage = JSON.parse(msgBuffer);
    io.sockets.emit('message', JSON.stringify(jsonMessage));
});
udpSocket.bind(udpPort, '127.0.0.1');

You can go to this link to see the error chrome has. http://postimg.org/image/xkv7a2kwb/

Does anyone have any ideas on how to fix this?

like image 968
batchi Avatar asked May 24 '26 05:05

batchi


1 Answers

This error usually occurs when you have incorrect Express config for static files.

From your client-side JavaScript I can see that you store your static files in public folder.

So somewhere on the server-side you should have something like this:

app.use('/public', express.static('/path/to/public'));

Doing this way http://localhost/public/audio/Bloom.mp3 request will be served with /path/to/public/audio/Bloom.mp3 file.

Caveat:

Since Express 4 there is "no more app.use(app.router)" and "All routing methods will be added in the order in which they appear". This means that you have to put the above line of code before first app.get(...), app.post(...), etc.

Hope this information will help someone.

like image 87
Oleg Avatar answered May 25 '26 18:05

Oleg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!