rowntreerob

bubble - audio recorder in html tag

Oct 22nd, 2021 (edited)
495
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // add the following script to an html widget that also contains html for buttons ( start, stop )
  2. <script>
  3. //Browser compatibility
  4. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  5. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  6. let streamObj;
  7. let config = {
  8.     bufferLen: 4096,
  9.     numChannels: 1,
  10.     mimeType: 'audio/mpeg'
  11. };
  12. let ctx;  
  13. let processor;
  14. let microphone;
  15. let holdbuffer = new Array();
  16. let audiodata;
  17. document.querySelector("#btnstart").onclick = startStream; // Wire up start button
  18. document.querySelector("#btnstop").onclick = stopStream; // Wire up stop button
  19.  
  20. function startStream() {
  21.     ctx = new AudioContext()
  22.     processor =
  23.     ctx.createScriptProcessor(config.bufferLen, config.numChannels, config.numChannels);
  24.     processor.connect(ctx.destination);
  25.       if (navigator.getUserMedia) {
  26.         //Request for the user media
  27.         navigator.getUserMedia(
  28.             { audio: true, video: false },
  29.             onSuccess,
  30.             onErrors
  31.         );
  32.     } else {
  33.         console.log("User media is not supported.");
  34.     }
  35.     console.log("start")
  36. }
  37.  
  38. let getBuffers = (event) => {
  39.     var buffers = [];
  40.     for (var ch = 0; ch < 1; ++ch)
  41.         buffers[ch] = event.inputBuffer.getChannelData(ch);
  42.     return buffers;
  43. }
  44.  
  45. function onSuccess(stream) {
  46.     //Play the media stream in the video element
  47.     streamObj = stream;
  48.     console.log(stream.getAudioTracks()[0].getSettings());
  49. microphone = ctx.createMediaStreamSource(stream);
  50. microphone.connect(processor);
  51. processor.onaudioprocess = function(event) {
  52.     var tdata = getBuffers(event);
  53.     holdbuffer.push(tdata);
  54. console.log(tdata[0].length)
  55. };
  56. }
  57.  
  58. function onErrors(error) {
  59.     //Handle the permission denied error in Chrome and 'Starting video failed' error in Firefox
  60.     if (error.name == "PermissionDeniedError" || error == "Starting video failed") {
  61.         alert("Media might already be in use");
  62.     } else { //Handle all other errors
  63.         console.log("error: ", error);
  64.     }
  65. }
  66.  
  67. function stopStream() {
  68.      streamObj.getAudioTracks()[0].stop();
  69.     ctx.close();
  70.     processor.disconnect();
  71.     audiodata = new Blob(holdbuffer, {type : 'audio/pcm'});
  72.     console.log("stop " +audiodata.size)
  73. }
  74. </script>
RAW Paste Data