I have a web page that is trying to play multiple video stream from two web cam that is attached with the system. Three Cameras attached with my system , one in an in-build camera in the system, second is a usb camera and third is a droid cam client. I can't play video from system cam and usb cam at a time, I mean droid cam always playing but only one of the other camera at a time.
for example:
Droid cam and USB Cam = works
Droid cam and System Camera( in built) = works
Usb and System Camera = not working
My Code is
let devices = await navigator.mediaDevices.enumerateDevices();
if (devices.length > 0) {
log(`Available Device Count ${devices.length}`);
for (const device of devices) {
let localContraints = { audio: false }
if (device.kind === "videoinput") {
localContraints.video = { deviceId: device.deviceId ? { exact: device.deviceId } : undefined };
var newStream = await navigator.mediaDevices.getUserMedia(localContraints).catch(err => console.log(err + device.label));
if (newStream) {
console.log(`Device Added ${device.label}`);
window.stream.addTrack(newStream.getVideoTracks()[0]);
}
}
}
}
else {
log(`No Devices Available`);
}
Error : could't load 'camera label'
two camera stream added in the window object one is always Droid Cam.
first of all I want know is this possible?
After digging into the issue i found the real problem and a solution. the real problem was asynchronous behavior of java script. so i rewrite the loop. This will help others who facing the similar issue.
$(document).ready(async () =>{
let leftVideo = document.querySelector('video#left');
let rightVideo = document.querySelector('video#right');
let middleVideo = document.querySelector('video#middle');
let videoElemArray = [leftVideo, middleVideo, rightVideo]
let devices = await navigator.mediaDevices.enumerateDevices();
let i = 0;
let videoIndx = 0;
await new Promise(async (resolve, reject) => {
try {
if (devices.length == 0) return resolve();
let funSync = async () => {
if (devices[i].kind === "videoinput") {
var newStream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { deviceId: devices[i].deviceId } });
videoElemArray[videoIndx].srcObject = newStream;
videoIndx++;
}
i++;
if (i == devices.length) return resolve();
else funSync();
}
funSync();
} catch (e) {
reject(e);
}
})
});
Related
I am building a video conferencing web application using WebRTC and I have implemented features for toggling the camera, microphone, and screen sharing. The camera and screen sharing features are working as expected, but I am having an issue with the microphone button.
The issue is that after using screen sharing and then stopping it, the microphone on/off button is not working properly. I am getting an error in the console saying
"Cannot read properties of undefined (reading 'enabled')".
Before using screen sharing, the microphone button works fine.
Here's my current code for handling the buttons:
let screenStream = null;
let localStream = null;
let audioTrack = null;
let pc = null;
// Toggle screen sharing on/off
document.getElementById("share-screen-btn").addEventListener("click", async () => {
try {
const localVideo = document.getElementById("localVideo");
const displayMediaOptions = {
video: true,
audio: true,
};
if (!screenStream) {
screenStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
const videoTracks = screenStream.getVideoTracks();
await pc.getSenders().find(sender => sender.track.kind === 'video').replaceTrack(videoTracks[0], videoTracks[0].clone());
localVideo.srcObject = screenStream;
document.getElementById("share-screen-btn").classList.remove("btn-danger");
document.getElementById("share-screen-btn").classList.add("btn-primary");
// Disable audio track from localStream
if (localStream) {
audioTrack = localStream.getAudioTracks()[0];
audioTrack.enabled = false;
}
} else {
const localVideoStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
const sender = pc.getSenders().find(sender => sender.track.kind === 'video');
const localVideoTrack = localVideoStream.getVideoTracks()[0];
const localAudioTrack = localVideoStream.getAudioTracks()[0];
const localStream = new MediaStream([localVideoTrack, localAudioTrack]);
await sender.replaceTrack(localVideoTrack);
localVideo.srcObject = localStream;
document.getElementById("share-screen-btn").classList.remove("btn-primary");
document.getElementById("share-screen-btn").classList.add("btn-danger");
screenStream.getTracks().forEach(track => track.stop());
screenStream = null;
// Set audioTrack from localAudioTrack
audioTrack = localAudioTrack;
}
} catch (e) {
console.error("Error sharing screen: ", e);
}
})
// Toggle microphone on/off
document.getElementById("mute-audio-btn").addEventListener("click", () => {
let localStream = document.getElementById("localVideo").srcObject;
if (localStream) {
let audioTrack = localStream.getAudioTracks()[0];
let enabled = audioTrack.enabled;
if (enabled) {
audioTrack.enabled = false;
document.getElementById("mute-audio-btn").innerHTML = '<i class="fa-solid fa-microphone-slash"></i>'
} else {
audioTrack.enabled = true;
document.getElementById("mute-audio-btn").innerHTML = '<i class="fa-solid fa-microphone"></i>'
}
}
})
// Toggle camera on/off
document.getElementById("mute-video-btn").addEventListener("click", () => {
let localStream = document.getElementById("localVideo").srcObject;
if (localStream) {
let videoTrack = localStream.getVideoTracks()[0];
let enabled = videoTrack.enabled;
if (enabled) {
videoTrack.enabled = false;
document.getElementById("mute-video-btn").innerHTML = '<i class="fa fa-video-slash"></i>';
} else {
videoTrack.enabled = true;
document.getElementById("mute-video-btn").innerHTML = '<i class="fa fa-video"></i>';
}
}
})
If I see it correctly then audioTrack or videoTrack is undefined at the time this happens.
Try and console.log() the arrays returned by localStream.getAudioTracks() or screenStream.getVideoTracks()
You may from there work your way up the chain.
And it seems to use audio while sharing the screen you are suppused to use addTrack
have a look here:
Is it possible broadcast audio with screensharing with WebRTC
I am pretty sure I did everything correct but when I try to play or download the file nothing plays. I am using web audio api to record audio from the microphone to a WAV format. I am using this library to create the .wav file. It seems like nothing is being encoded.
navigator.mediaDevices.getUserMedia({
audio: true,video:false
})
.then((stream) => {
var data
context = new AudioContext()
var source = context.createMediaStreamSource(stream)
var scriptNode = context.createScriptProcessor(8192, 1, 1)
source.connect(scriptNode)
scriptNode.connect(context.destination)
encoder = new WavAudioEncoder(16000,1)
scriptNode.onaudioprocess = function(e){
data = e.inputBuffer.getChannelData('0')
console.log(data)
encoder.encode(data)
}
$('#stop').click(()=>{
source.disconnect()
scriptNode.disconnect()
blob = encoder.finish()
console.log(blob)
url = window.URL.createObjectURL(blob)
// audio source
$('#player').attr('src',url)
// audio control
$("#pw")[0].load()
})
})
I figured it out! To help anyone who needs to do the same thing. It uses Web Audio API and this javascript library
navigator.mediaDevices.getUserMedia({
audio: true,video:false
})
.then((stream) => {
context = new AudioContext()
var source = context.createMediaStreamSource(stream)
var rec = new Recorder(source)
rec.record()
$('#stop').click(()=>{
rec.stop()
blob = rec.exportWAV(somefunction) // exportWAV() returns your file
})
use recordRTC for recording video and audio, I used in my project, it's working well, here is the code to record audio using recordrtc.org
startRecording(event) { // call this to start recording the Audio( or video or Both)
this.recording = true;
let mediaConstraints = {
audio: true
};
// Older browsers might not implement mediaDevices at all, so we set an empty object first
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
// Some browsers partially implement mediaDevices. We can't just assign an object
// with getUserMedia as it would overwrite existing properties.
// Here, we will just add the getUserMedia property if it's missing.
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
// First get ahold of the legacy getUserMedia, if present
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
// Some browsers just don't implement it - return a rejected promise with an error
// to keep a consistent interface
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
// Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(successCallback.bind(this), errorCallback.bind(this));
}
successCallback(stream: MediaStream) {
var options = {
type: 'audio'
};
this.stream = stream;
this.recordRTC = RecordRTC(stream, options);
this.recordRTC.startRecording();
}
errorCallback(stream: MediaStream) {
console.log(stream);
}
stopRecording() { // call this to stop recording
this.recording = false;
this.converting = true;
let recordRTC = this.recordRTC;
if(!recordRTC) return;
recordRTC.stopRecording(this.processAudio.bind(this));
this.stream.getAudioTracks().forEach(track => track.stop());
}
processAudio(audioVideoWebMURL) {
let recordRTC = this.recordRTC;
var recordedBlob = recordRTC.getBlob(); // you can save the recorded media data in various formats, refer the link below.
console.log(recordedBlob)
this.recordRTC.save('audiorecording.wav');
let base64Data = '';
this.recordRTC.getDataURL((dataURL) => {
base64Data = dataURL.split('base64,')[1];
console.log(RecordRTC.getFromDisk('audio', function(dataURL,type) {
type == 'audio'
}));
console.log(dataURL);
})
}
Note that you cannot record the audio/video from the live site in Google Chrome unless your site is https enabled
I had to write a program for facial recognition in JavaScript , for which I used the opencv4nodejs API , since there's NOT many working examples ; Now I somehow want to record and save the stream (for saving on the client-side or uploading on the server) alongwith the audio. This is where I am stuck. Any help is appreciated.
In simple words I need to use the Webcam input for multiple purposes , one for facial recognition and two to somehow save , latter is what i'm unable to do. Also in the worst case, If it's not possible Instead of recording and saving the webcam video I could also save the Complete Screen recording , Please Answer if there's a workaround to this.
Below is what i tried to do, But it doesn't work for obvious reasons.
$(document).ready(function () {
run1()
})
let chunks = []
// run1() for uploading model and for facecam
async function run1() {
const MODELS = "/models";
await faceapi.loadSsdMobilenetv1Model(MODELS)
await faceapi.loadFaceLandmarkModel(MODELS)
await faceapi.loadFaceRecognitionModel(MODELS)
var _stream
//Accessing the user webcam
const videoEl = document.getElementById('inputVideo')
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(
(stream) => {
_stream = stream
recorder = new MediaRecorder(_stream);
recorder.ondataavailable = (e) => {
chunks.push(e.data);
console.log(chunks, i);
if (i == 20) makeLink(); //Trying to make Link from the blob for some i==20
};
videoEl.srcObject = stream
},
(err) => {
console.error(err)
}
)
}
// run2() main recognition code and training
async function run2() {
// wait for the results of mtcnn ,
const input = document.getElementById('inputVideo')
const mtcnnResults = await faceapi.ssdMobilenetv1(input)
// Detect All the faces in the webcam
const fullFaceDescriptions = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceDescriptors()
// Training the algorithm with given data of the Current Student
const labeledFaceDescriptors = await Promise.all(
CurrentStudent.map(
async function (label) {
// Training the Algorithm with the current students
for (let i = 1; i <= 10; i++) {
// console.log(label);
const imgUrl = `http://localhost:5500/StudentData/${label}/${i}.jpg`
const img = await faceapi.fetchImage(imgUrl)
// detect the face with the highest score in the image and compute it's landmarks and face descriptor
const fullFaceDescription = await faceapi.detectSingleFace(img).withFaceLandmarks().withFaceDescriptor()
if (!fullFaceDescription) {
throw new Error(`no faces detected for ${label}`)
}
const faceDescriptors = [fullFaceDescription.descriptor]
return new faceapi.LabeledFaceDescriptors(label, faceDescriptors)
}
}
)
)
const maxDescriptorDistance = 0.65
const faceMatcher = new faceapi.FaceMatcher(labeledFaceDescriptors, maxDescriptorDistance)
const results = fullFaceDescriptions.map(fd => faceMatcher.findBestMatch(fd.descriptor))
i++;
}
// I somehow want this to work
function makeLink() {
alert("ML")
console.log("IN MAKE LINK");
let blob = new Blob(chunks, {
type: media.type
}),
url = URL.createObjectURL(blob),
li = document.createElement('li'),
mt = document.createElement(media.tag),
hf = document.createElement('a');
mt.controls = true;
mt.src = url;
hf.href = url;
hf.download = `${counter++}${media.ext}`;
hf.innerHTML = `donwload ${hf.download}`;
li.appendChild(mt);
li.appendChild(hf);
ul.appendChild(li);
}
// onPlay(video) function
async function onPlay(videoEl) {
run2()
setTimeout(() => onPlay(videoEl), 50)
}
I'm not familiar with JavaScript. But in general only one program may communicate with the camera. You will probably need to write a server which will read the data from the camera. Then the server will send the data to your facial recognition, recording, etc.
I am trying to figure out how to change the microphone or webcam while you are in a videochat with someone.
I have been now trying for a few days and nothing works.
I was following this example, but it seems it is much harder to achieve the change while someone is already connected.
The issues I have: If I change the mic the sound is lost/the mic doesnt react at all. I also cannot change it back to the default.
A similar thing happens if I change the webcam. The stream hangs, the last frame is seen.
I get no error message, in fact it tells me that the changes were successful.
Changing the webcam/mic WORKS before the call is established
Here is the relevant codeblock. Everywhere I am reading just create new constraints and give the desired deviceId to the audio/video stream.:
function ChangeDevice() {
if (localStream) {
localStream.getTracks().forEach(track => {
track.stop();
});
}
var audioSource = audioInputSelect.value;
var videoSource = videoSelect.value;
console.log(videoSource);
console.log(audioSource);
const newConstraints = {
audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(newConstraints).then(gotStream).then(gotDevices).catch(handleError);
}
function gotStream(stream) {
console.log('Adding local stream.');
localStream = stream;
localVideo.srcObject = stream;
sendMessage(['got user media', room]);
if (isInitiator) {
maybeStart();
}
return navigator.mediaDevices.enumerateDevices(); // I added this
}
I think these two are the relevant functions, ChangeDevice is called when I select a new device from a dropdown. The id's are correct.
Here is the whole code I use:
pastebin.com/6JrK4jJD
Luckily replaceTrack seems to work now on all browsers, so there is no need to renegotiate.
I had to edit my gotStream function like this:
function gotStream(stream) {
// If already started
// Need this if webcam or mic changes
if (isStarted) {
var videoTrack = stream.getVideoTracks()[0];
var audioTrack = stream.getAudioTracks()[0];
var sender = pc.getSenders().find(function(s) {
return s.track.kind == videoTrack.kind;
});
var sender2 = pc.getSenders().find(function(s) {
return s.track.kind == audioTrack.kind;
});
console.log('found sender:', sender);
sender.replaceTrack(videoTrack);
sender2.replaceTrack(audioTrack);
localStream = stream;
localVideo.srcObject = stream;
} else {
console.log('Adding local stream.');
localStream = stream;
localVideo.srcObject = stream;
sendMessage(['got user media', room]);
if (isInitiator) {
maybeStart();
}
}
return navigator.mediaDevices.enumerateDevices(); // I added this
}
I'm working on a project and I require to send an audio stream to a Node.js server. I'm able to capture microphone sound with this function:
function micCapture(){
'use strict';
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
if (window.URL) {
video.src = window.webkitURL.createObjectURL(stream);
} else {
video.src = stream;
}
//Send audio stream
//server.send(stream);
}
function errorCallback(error) {
console.log('navigator.getUserMedia error: ', error);
}
navigator.getUserMedia(constraints, successCallback, errorCallback);
}
As you can see, I'm able to capture audio and play it on the website.
Now I want to send that audio stream to a Node.js server, and send it back to other clients. Like a voicechat, but I don't want to use WebRTC as I need the stream in the server. How can I achieve this? Can I use socket.io-stream to do this? In the examples I saw, they recorded the audio, and sent a file, but I need "live" audio.
I have recently done live audio upload using socket.io from browser to server. I am going to answer here in case someone else needs it.
var stream;
var socket = io();
var bufferSize = 1024 * 16;
var audioContext = new AudioContext();
// createScriptProcessor is deprecated. Let me know if anyone find alternative
var processor = audioContext.createScriptProcessor(bufferSize, 1, 1);
processor.connect(audioContext.destination);
navigator.mediaDevices.getUserMedia({ video: false, audio: true }).then(handleMicStream).catch(err => {
console.log('error from getUserMedia', err);
});
handleMicStream will run when user accepts the permission to use microphone.
function handleMicStream(streamObj) {
// keep the context in a global variable
stream = streamObj;
input = audioContext.createMediaStreamSource(stream);
input.connect(processor);
processor.onaudioprocess = e => {
microphoneProcess(e); // receives data from microphone
};
}
function microphoneProcess(e) {
const left = e.inputBuffer.getChannelData(0); // get only one audio channel
const left16 = convertFloat32ToInt16(left); // skip if you don't need this
socket.emit('micBinaryStream', left16); // send to server via web socket
}
// Converts data to BINARY16
function convertFloat32ToInt16(buffer) {
let l = buffer.length;
const buf = new Int16Array(l / 3);
while (l--) {
if (l % 3 === 0) {
buf[l / 3] = buffer[l] * 0xFFFF;
}
}
return buf.buffer;
}
Have your socket.io server listen to micBinaryStream and you should get the data. I needed the data as a BINARY16 format for google api if you do not need this you can skip the function call to convertFloat32ToInt16().
Important
When you need to stop listening you MUST disconnect the the processor and end the stream. Run the function closeAll() below.
function closeAll() {
const tracks = stream ? stream.getTracks() : null;
const track = tracks ? tracks[0] : null;
if (track) {
track.stop();
}
if (processor) {
if (input) {
try {
input.disconnect(processor);
} catch (error) {
console.warn('Attempt to disconnect input failed.');
}
}
processor.disconnect(audioContext.destination);
}
if (audioContext) {
audioContext.close().then(() => {
input = null;
processor = null;
audioContext = null;
});
}
}
it's an old time question, i see. I'm doing the same thing (except my server doesn't run node.js and is written in C#) and stumbled upon this.
Don't know if someone is still interested but i've elaborated a bit. The current alternative to the deprecated createScriptProcessor is the AudioWorklet interface.
From: https://webaudio.github.io/web-audio-api/#audioworklet
1.32.1. Concepts
The AudioWorklet object allows developers to supply scripts (such as JavaScript or >WebAssembly code) to process audio on the rendering thread, supporting custom >AudioNodes. This processing mechanism ensures synchronous execution of the script >code with other built-in AudioNodes in the audio graph.
You cannot implement interfaces in Javascript as far as i know but you can extend a class derived from it.
And the one we need is: https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletProcessor
So i did write a processor that just mirrors the output with the input values and displays them.
class CustomAudioProcessor extends AudioWorkletProcessor {
process (inputs, outputs, parameters) {
const input = inputs[0];
const output = output[0];
for (let channel = 0; channel < input.length; ++channel) {
for (let i = 0; i < input[channel].length; ++i) {
// Just copying all the data from input to output
output[channel][i] = input[channel][i];
// The next one will make the app crash but yeah, the values are there
// console.log(output[channel][i]);
}
}
}
}
The processor must then be placed into the audio pipeline, after the microphone and before the speakers.
function record() {
constraints = { audio: true };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
audioCtx = new AudioContext();
var source = audioCtx.createMediaStreamSource(stream);
audioCtx.audioWorklet.addModule("custom-audio-processor.js").then(() => {
customAudioProcessor = new AudioWorkletNode(audioCtx, "custom-audio-processor");
source.connect(customAudioProcessor);
customAudioProcessor.connect(audioCtx.destination);
})
audioCtx.destination.play();
Works! Good luck! :)