我创建了一个小项目来使用Socket.io传输实时音频。问题是这只有在我在同一个chrome窗口中测试时才有效。当另一台计算机试图收听或广播时,它不能。这是另一台计算机中显示的消息:
GET blob:https://server/ce74cfe7-bb9c-40b0-9cb0-1138b22b1b11 404 (Not Found)
这是main.js(网站)中的代码:
$(document).ready(function(){
var socket = io("https://server:4000", verify=false);
socket.on('audio stream', function(name, blob){
var video = document.querySelector('video');
video.src = blob;
});
$('#ptt').click(function(){
micOn();
document.getElementById("ptt").disabled = true;
document.getElementById("ptt-off").disabled = false;
});
$('#ptt-off').click(function(){
stream.getAudioTracks()[0].stop();
document.getElementById("ptt").disabled = false;
document.getElementById("ptt-off").disabled = true;
});
function micOn(){
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var constraints = {
audio: true,
video: false
};
var video = document.querySelector('video');
function successCallback(stream) {
window.stream = stream; // stream available to console
var blob = window.URL.createObjectURL(stream);
socket.emit('audio stream', myName, blob);
}
function errorCallback(error) {
console.log('navigator.getUserMedia error: ', error);
}
navigator.getUserMedia(constraints, successCallback, errorCallback);
}
});
这是服务器上的代码(index.js):
socket.on('audio stream', function(name, blob){
console.log(name + ' is broadcasting audio');
socket.broadcast.emit('audio stream', name, blob);
});
答案 0 :(得分:0)
要使用Socket.io进行流式传输,您需要使用socket.io-stream库。
根据官方文件: socket.io-stream
使用下面的文件从socket.io-stream站点获得的一个简单示例。
//For streaming between server and client, you will send stream instances first. To receive streams, you just wrap socket with socket.io-stream, then listen any events as usual.
//SERVER:
var io = require('socket.io').listen(80);
var ss = require('socket.io-stream');
var path = require('path');
io.of('/user').on('connection', function(socket) {
ss(socket).on('profile-image', function(stream, data) {
var filename = path.basename(data.name);
stream.pipe(fs.createWriteStream(filename));
});
});
//The function createStream() returns a new stream which can be sent by emit().
//CLIENT:
var io = require('socket.io-client');
var ss = require('socket.io-stream');
var socket = io.connect('http://example.com/user');
var stream = ss.createStream();
var filename = 'profile.jpg';
ss(socket).emit('profile-image', stream, {name: filename});
fs.createReadStream(filename).pipe(stream);
//You can stream data from a client to server, and vice versa.
// send data
ss(socket).on('file', function(stream) {
fs.createReadStream('/path/to/file').pipe(stream);
});
// receive data
ss(socket).emit('file', stream);
stream.pipe(fs.createWriteStream('file.txt'));