As far as I know the only way to capture audio from user microphone at real time is by using Flash plugin (need to get user permission) or Java.
Does someone know any other way like HTML5 or JavaScript? All my program is built with HTML5 and I don't want to use another technology.
You can use navigator.getUserMedia.
For example:
(function(){
getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
getMedia(
{
video: false,
audio: true
},
function (localMediaStream) {
var video = document.createElement('video');
video.src = window.URL.createObjectURL(localMediaStream);
video.onloadedmetadata = function(e) {
//deal with data
};
},
function (err) {
console.log("The following error occured: " + err);
}
);
})();
See Mozilla Developer Network for more info.
Note: This only works in Chrome, recent Firefox (20+), and Opera (12+), but not in Internet Explorer.
Related
I am developing a web application for video recording.
I have tried the below code but the problem is it working fine with a external camera, but in the laptops inbuilt camera with the same Browser it is giving no Object found error.
I am using Firefox 60.6.1
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
//load the stream in the video variable
video.srcObject = stream;
//load the stream in revokeAccess variable
revokeAccess=stream;
//video playback
video.play();
/*
Optional to avoid the dual audio disturbance. Playback audio is muted
*/
video.muted= true;
if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
var options = {mimeType: 'video/webm;codecs=vp9'};
console.log("using vp9");
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
var options = {mimeType: 'video/webm;codecs=h264'};
console.log("using h264");
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
var options = {mimeType: 'video/webm;codecs=vp8',videoBitsPerSecond : 1500000,audioBitsPerSecond : 160000};
console.log("using vp8");
}else{
console.log('isTypeSupported is not supported, using default codecs for browser');
}
//load the stream and type of video in the function
mediaRecorder = new MediaRecorder(stream,options);
//handle the data availability
mediaRecorder.ondataavailable = handleDataAvailable;
//Start the recording
mediaRecorder.start();
alert("Started Recording");
//push the data into chunks(array)
function handleDataAvailable(event) {
if (event.data.size > 0) {
recordedChunks.push(event.data);
console.log(recordedChunks);
} else {
alert(event);
}
}
//disable the Start Recording button
document.getElementById("startRecording").disabled = true;
})
.catch(function(error) {
//handle the device not found exception
alert("Camera not Found !! Please connect camera properly");
console.log(error);
});
}
I want the application to be working in each platform.
Hi All Developers Thanks for your support and quick response.
I fixed the issues using the below adapter addition in the code.
var getUserMedia = navigator.getUserMedia ||
navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia;
If you want to support legacy browser, check following.
https://github.com/webrtcHacks/adapter
WebRTC adapter
adapter.js is a shim to insulate apps from spec changes and prefix
differences. In fact, the standards and protocols used for WebRTC
implementations are highly stable, and there are only a few prefixed
names. For full interop information, see webrtc.org/web-apis/interop.
This repository used to be part of the WebRTC organisation on github
but moved. We aim to keep the old repository updated with new
releases.
Also, you can check your hardware environment form firefox.
In the address bar on browser type following
about:support
I am using getusermedia to record audio in my website. I've included the javascript of getusermedia. The record function works fine on website but doesn't even popup for permission in when opened on mobile.
var constraints = {
audio: true,
video: false
}
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
permissiongiven = 1;
});
this is the sample code which prompt me for permission but doesn't work on mobile.
How can I make it work on both device. Any help is appreciated.
Thanks.
Edit :- The code is now working fine on mobile as well. Maybe it was solved from chrome updates or security certificates of website. Thanks all for help.
Note that on mobile devices, you have to use SSL to use getUserMedia(). Check out if you're accessing your website with a http:// prefix. Try change it to https:// and it should work fine.
I found this website useful in answering this question
https://caniuse.com/#search=getusermedia
It says getUserMedia only supported from Chrome for Android version 70 (released Oct 16 2018)
Check MDN, then make sure your browser supports it. You need Chrome for Android 52+ it says. FWIW 68 works for me.
You should also feature-check and catch errors:
if (!navigator.mediaDevices) {
console.log("Sorry, getUserMedia is not supported");
return;
}
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => permissiongiven = 1)
.catch(error => console.log(error));
Depending on the error you get, we might learn more.
NotFoundError means no camera or mic detected on the device.
NotAllowedError means user permission not granted, or you're in an iframe or not https.
navigator.mediaDevices.getUserMedia Browser compatibility
i had no idea that navigator.getUserMedia was deprecated (at least for Samsung, which is what i was testing on), and i found this article on web audio with a code sample that i barely modified:
function initGetUserMedia() {
navigator.mediaDevices = navigator.mediaDevices || {}
navigator.mediaDevices.getUserMedia = navigator.mediaDevices.getUserMedia || function(constraints) {
let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia not supported by this browser'));
} else {
return new Promise((resolve, reject) => {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
}
Try this code with ssl site:
<script>var constraints = {audio: true, video: false}
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {{permissiongiven = 1;});</script>
I'm developing an application that allows voice recording in the web browser. This is working fine on most browsers but I have some issues with iOS Safari.
Below you can find an extract of the code, it is not complete but it gives an idea of what's going on.
//Triggered when the user clicks on a button that start the recording
function startRecording() {
//Create new audio context
let audioContext = new (window.AudioContext || window.webkitAudioContext);
//Hack polyfill media recorder to re-use the audioContex
window.NewMediaRecorder.changeAudioContext(audioContext);
navigator.mediaDevices.enumerateDevices().then(function (devices) {
console.log('loaded audio devices');
console.log(devices);
devices = devices.filter((d) => d.kind === 'audioinput');
console.log(devices);
console.log('chosen device: ' + devices[0].deviceId);
navigator.mediaDevices.getUserMedia({
audio: {
deviceId : {
exact : devices[0].deviceId
}
}
}).then(function (stream) {
console.log(stream);
let recorder = new NewMediaRecorder(stream);
recorder.addEventListener('dataavailable', function (e) {
document.getElementById('ctrlAudio').src = URL.createObjectURL(e.data);
});
recorder.start();
console.log('stop listening after 15 seconds');
setTimeout(function () {
console.log('15 seconds passed');
console.log("Force stop listening");
recorder.stop();
recorder.stream.getTracks()[0].stop();
}, 15000);
});
});
}
For the record, I'm using audio recorder polyfill (https://ai.github.io/audio-recorder-polyfill/) in order to achieve recording, as MediaRecorder is not yet available on Safari.
The recorder works fine on all navigators (this including OS X Safari), yet on iOS Safari it only records noice. If I set the volume of my speakers at maximal level I can hear myself speak, but it is from "very far away".
All the online dictaphones/recorders that I found have the same issue, they always recording noise. (Tested with an iPhone 5S, 5SE and X, all up to date).
I'm a bit desperate because I already did a lot of research, but I didn't find any solution for this issue.
As required, the AudioContext is created on a user event (in this case a touch on a button).
I even tried to change the gain of but that didn't help.
Trying to access the audio without setting a media device isn't helping.
navigator.mediaDevices.getUserMedia({audio: true})
I am trying to access the native camera with HTML5 to capture images for my web application it was working fine in my laptop but in mobile device it is not working..
I am testing it with opera 12.0 in Android Gingerbread, the browser asks me whether to allow camera or not. But after allowing it doesn't show anything in the video tag.Here is my code,
The HTML:
<video autoplay id="vid" style="" width="200" height="150"></video>
<canvas id="canvas" width="640" height="480" style="display:none;""></canvas><br>
<input type="button" value="Take Picture" onclick="snapshot()"/>
the JavaScript:
var video = document.querySelector("video");
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
var onCameraFail = function (e) {
console.log('Camera did not work.', e);
};
function snapshot() {
if (localMediaStream) {
ctx.drawImage(video, 0, 0);
}
var strDataURI = canvas.toDataURL("image/png");
$('#canvas_image').src = strDataURI;
$.ajax({type: 'POST',url: "<?php echo base_url().'my_profile/save_image' ?>",data: {strDataURI:strDataURI },
success: function(resultData) {
location.reload();
}
});}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia({video:true}, function (stream) {
video.src = window.URL.createObjectURL(stream);
localMediaStream = stream;
}, onCameraFail);
I've been using Opera Mobile 12 to do a similar job for a while and recently noticed this issue with code that used to work fine. For me it fails on Opera Mobile 12.10. It seems that window.URL.createObjectURL(stream) is returning about:streamurl where previously (from memory) it returned a blob style URL.
I only noticed it in passing because we have since moved all our customers over to Chrome Beta. Despite being a beta we've found it much more stable (and more performant) than Opera. The only issue is that the dimensions of video it picks up from the webcam are slightly different to Opera, but we can work with that.
This doesn't directly answer your question, but if possible I'd suggest moving over to Chrome Beta (and Chrome Stable once it gets GetUserMedia support) rather than struggling with Opera.
I'm trying to take video and audio from my webcam using getMedia(), but my browser always block the function. I'm using Google Chrome, and this icon appears near Favorite Icon: http://puu.sh/4pLAk.png
The JS is an example of MDN: https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getUserMedia
HTML:
<!DOCTYPE html>
<html>
<body>
<button onClick="getMedia()">Ok</button>
<body>
<html>
JS:
function getMedia()
{
navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia (
// constraints
{
video: true,
audio: true
},
// successCallback
function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
video.onloadedmetadata = function(e) {
// Do something with the video here.
};
},
// errorCallback
function(err) {
console.log("The following error occured: " + err);
}
);
}
What I'm doing wrong?
When prompted for camera or mic access and you hit the "Deny" button, Chrome will save that choice on future calls to getUserMedia on that site. Yo'll want to click on the video icon that you mentioned and change the permissions to allow camera and/or mic access. See this page for an example of what this looks like.
I encountered similar problem, but related to microphone access.
As tom vLine answered, Chrome blocks device access if you serve your file via file://(note that on Microsoft Edge and Firefox it worked via file:://).
One solution i've found for Chrome:
open chrome an type in the URL chrome://version/
copy the value of "Command Line" field in your command line and append
--allow-file-access-from-files and run it
after Chrome opened and enter your file:// url.
For starting Chrome always like that, right click on Chrome icon, and then click on properties. In the Shortcut tab append to the Target value all the command line parameters from 2.
Hope this helped someone :-)