Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // add the following script to an html widget that also contains html for buttons ( start, stop )
- <script>
- //Browser compatibility
- navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
- window.AudioContext = window.AudioContext || window.webkitAudioContext;
- let streamObj;
- let config = {
- bufferLen: 4096,
- numChannels: 1,
- mimeType: 'audio/mpeg'
- };
- let ctx;
- let processor;
- let microphone;
- let holdbuffer = new Array();
- let audiodata;
- document.querySelector("#btnstart").onclick = startStream; // Wire up start button
- document.querySelector("#btnstop").onclick = stopStream; // Wire up stop button
- function startStream() {
- ctx = new AudioContext()
- processor =
- ctx.createScriptProcessor(config.bufferLen, config.numChannels, config.numChannels);
- processor.connect(ctx.destination);
- if (navigator.getUserMedia) {
- //Request for the user media
- navigator.getUserMedia(
- { audio: true, video: false },
- onSuccess,
- onErrors
- );
- } else {
- console.log("User media is not supported.");
- }
- console.log("start")
- }
- let getBuffers = (event) => {
- var buffers = [];
- for (var ch = 0; ch < 1; ++ch)
- buffers[ch] = event.inputBuffer.getChannelData(ch);
- return buffers;
- }
- function onSuccess(stream) {
- //Play the media stream in the video element
- streamObj = stream;
- console.log(stream.getAudioTracks()[0].getSettings());
- microphone = ctx.createMediaStreamSource(stream);
- microphone.connect(processor);
- processor.onaudioprocess = function(event) {
- var tdata = getBuffers(event);
- holdbuffer.push(tdata);
- console.log(tdata[0].length)
- };
- }
- function onErrors(error) {
- //Handle the permission denied error in Chrome and 'Starting video failed' error in Firefox
- if (error.name == "PermissionDeniedError" || error == "Starting video failed") {
- alert("Media might already be in use");
- } else { //Handle all other errors
- console.log("error: ", error);
- }
- }
- function stopStream() {
- streamObj.getAudioTracks()[0].stop();
- ctx.close();
- processor.disconnect();
- audiodata = new Blob(holdbuffer, {type : 'audio/pcm'});
- console.log("stop " +audiodata.size)
- }
- </script>
Add Comment
Please, Sign In to add comment