Live-recorded base64-encoded audio from MediaRecorder is broken

I wrote a simple page on js and php to live record audio from microphone. Logic is simple:

JS

  1. Get chunk of data from mic;
  2. Base64 encode it and urlencode it;
  3. Send it via POST request;

PHP

  1. Base64 decode data;
  2. (re)Write to .ogg file;
  3. Repeat 1 after delay.

The data is successfully written to file, but when I try to play it, player says that file is broken.

The blob solution from Mozilla guide is worked for me, I want exactly PHP solution with saving (rewriting) to file.

The full code below, what am I doing wrong?

<?php
if(isset($_POST["data"]))
{
file_put_contents("r.ogg", base64_decode($_POST["data"]));
exit;   
}
?>

<script>
var mediaRecorder = null;
let chunks = [];

if (navigator.mediaDevices &amp;&amp; navigator.mediaDevices.getUserMedia) {
   console.log('getUserMedia supported.');
   navigator.mediaDevices.getUserMedia (
      {
         audio: true
      })
      .then(function(stream) {
        mediaRecorder = new MediaRecorder(stream);
        mediaRecorder.start(2000);
        
        mediaRecorder.ondataavailable = function(e) {
            chunks.push(e.data);
            const blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
            chunks = [];
            var reader = new FileReader();
            reader.readAsDataURL(blob); 
            reader.onloadend = function() {
            var data = reader.result.split(";base64,")[1]; 
            requestp2("a.php", "data="+encodeURIComponent(data));
            }
}
      })
      .catch(function(err) {
         console.log('The following getUserMedia error occurred: ' + err);
      }
   );
} else {
   console.log('getUserMedia not supported on your browser!');
}

function requestp2(path, data)
{
var http = new XMLHttpRequest();
http.open('POST', path, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.send(data);
}
</script>

call props function with parmeters from child

I want to call function with paramter from child compponent, i pass the function as a props and when i call this function its get to her but the paramter that i pass to the function is undiffend.

how can i call this function and send to her parmetrs?

here is my code:

perent function:

  async function doSomething(param){
//here i see in debug that param is undiffend
var do = param*2
console.log(do)
}

the call of the child componnet:

<child doSomething ={()=>doSomething()}/>

child:

export default function child(props) {
    const { doSomething} = props;
return (
            <div  onClick={() => doSomething(3)}>
           <button></button>
            </div>
    
)
 }

wrong date on conversion toISOString()

I am confused why on converting “8/20/2021” to ISO(cosmosDB format) I am getting “2021-08-19T18:30:00.000Z”?

const event = new Date('8/20/2021');
console.log(event.toISOString()); //"2021-08-19T18:30:00.000Z"

all the date are saved as string in my cosmosdb and hence I was not able to filter based on given date range and as result we ended up converting string to Date but now when I am trying to convert in to cosmos db expected format it gives me incorrect or may be correct date to update my database.

should I go ahead and update DB to ‘2021-08-19T18:30:00.000Z’ inplace of ‘8/20/2021’? or it should be ‘2021-08-20T00:00:00.000Z’?

please suggest

Why add new property on prototype is different from replace the prototype object in JavaScript

If I have a JavaScript constructor function:

function Foo() {}
Foo.prototype.bar = 123

Now I create a new object from Foo and change the bar property on prototype object.

const foo = new Foo()
Foo.prototype.bar = 321
console.log(foo.bar) // 321

But If I replace Foo.prototype with a object like this:

const foo = new Foo()
Foo.prototype = { bar: 321 }
console.log(foo.bar) // 123

Why the two code snippets’ output is different?

How to synchronously retrieve website in JS?

I have a synchronous function myFunction in which I need to retrieve the contents of a website. However, the async parameter I’m currently using is deprecated and I’m only aware of async AJAX requests. Thus I’m looking for a better solution how I can wait for the asynchronous call to finish and process the result synchronously.

The myFunction function is embedded in a library that I cannot modify. Thus there are the following limitations:

  • I cannot turn myFunction into a async function
  • I cannot use any third-party libraries, only plain javascript and jQuery
    var myFunction = function(url) {
        var mydata = false;

        $.get(
            {
                url: url,
                async: false
            })
            .done(content => {
                // Do something with content.

                if(content === 'xyz') {
                     mydata = content;
                     return;
                }
            });

        return mydata;
    };

I have already looked into Promises and async/await but I couldn’t find a good solution for wrapping async calls. I also didn’t found another method that can make synchronous Get requests. What’s the best way to implement this?

Adding to an Array and then storing and using the Array in a Chrome Extension across websites

I have the following code

let exampleArr = JSON.parse(localStorage.getItem("persons") || "[]");

let input = prompt("Write Any String");

exampleArr.push(input);

localStorage.setItem("exampleArr ", JSON.stringify(exampleArr ));

console.log(exampleArr);

To read user input and store into an array. However, because this uses local storage the Array is different from website to website. How would I make this work with ALL websites where if I add something to the exampleArr it will be like that for ALL websites? I have tried using the Chrome Storage Sync documentation found here

https://developer.chrome.com/docs/extensions/reference/storage/

But end up getting errors.

Prevent Typescript from checking entire classes to save time?

Typescript is taking a long time to run, so I used generateTrace from https://github.com/microsoft/TypeScript/pull/40063

It showed that most of the time was comparing complicated classes with their subclasses. E.g. one of the classes is the base Objection model (https://github.com/vincit/objection.js), which is the base class that all my models inherit.

E.g. I have code like:

class User extends Model {}

function doSomething(model: typeof Model) {}

doSomething(User);

I have ~50 models. I think the first time TS encounters each model is slow, then it caches it. It takes about 5s for TS to compare a specific model with the base Model. The Model uses types from several libraries. Here’s a screenshot of the trace, it takes 5min just to compare each model with Model:

enter image description here

Is there a way to get TS to stop comparing Model with itself? I.e. since User extends Model, there’s no need to check the fields it inherited.

why file path dosnt apear when i run google app script code

This is my gs code:

function onOpen(){
  var ui = SpreadsheetApp.getUi();
  var menu = ui.createMenu("bot")
  menu.addItem("test", "runForm")
  menu.addToUi();
}
    
function runForm() {
  var html = HtmlService.createHtmlOutputFromFile('picbox')
  SpreadsheetApp.getUi().showModelessDialog(html, 'form');
}
    
 function f(filePath) {
    SpreadsheetApp.getActiveSheet().getRange("A15").setValue(filePath)
    return true;
 } 

and this is my html code:
picbox.html:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body> 
    <input type="file" id="file123" />
    <input type="button" value="send file path"  onClick="func();"/>   
    <script>
      function func() {
        var a = document.getElementById("file123").Value
        google.script.run
        .withSuccessHandler(function(){google.script.host.close();})
        .f(a);
      }
    </script>
    </body>
</html>

when i run it the form apear but the file path dosnt shown on A15 cell. i know that f function calld and working i jusr dont know why the file path dont written.

Simplifying IF/ELSE condition

I want to ask how can I simplify my code? It seems hard to read and has too much if-else condition here. Any way to simplify the code?

if (e.shiftKey && this.idx > 0) {
  this.idx= this.idx - 1;
} else if (!e.shiftKey && this.idx < trapFocus.length - 1) {
  this.idx = this.idx + 1;
} else if (!e.shiftKey && this.idx < trapFocus.length + 1) {
  this.idx= this.idx - 2;
} else if (e.shiftKey && this.idx > - 1) {
  this.idx= this.idx + 2;
}

How do i Change the a tag href using js or jquery

Im trying to change the a tag href once clicked on it.

    <div class="yotpo-bottomline pull-left  star-clickable" tabindex="0">  
        <span class="yotpo-stars"> 
            <span class="yotpo-icon yotpo-icon-star rating-star pull-left"></span>
            <span class="sr-only">4.0 star rating</span>
        </span>  
        <a href="javascript:void(0)" class="text-m" aria-label="2 reviews" tabindex="-1">2 Reviews</a>   
    </div>  
</div>

CSS backdrop-filter works only if you DON’T set background-color to transparent

I’ve got a greyscale backdrop-filter applied to a .cover behind one of my overlaid menus. I sometimes, with JavaScript, want to set the .cover‘s background-color to an opaque black to darken the background, too.

I have the following CSS being applied to the cover:

body {
    --darkMode: transparent;
}
.cover {
    -webkit-backdrop-filter: grayscale(100%);
    backdrop-filter: grayscale(100%);
    background-color: var(--darkMode); /* Notable Line */
}

The JavaScript that sets the --darkMode variable is just document.body.style.setProperty("--darkMode", "rgba(0, 0, 0, 0.5)");

However, when darkMode is not enabled, and therefore the .cover‘s background-color is transparent, the backdrop-filters don’t work at all, even though when the “Notable Line” is removed, they work perfectly!

Thanks for any insights you might have, and have a splendid day, person who was willing to read this question.

Why does recursive/nested `setTimeout` does not stop execution without an `else` statement?

I am learning to use recursive setTimeout function.

My task is to create a function that takes 2 number arguments, from and to and prints each number in between to the console, one at the time with the delay of 1 second in between.

My question is, why function printNumbers1 does not stop execution after printing number 4 to the console? The assumption is that the timerID is incorrect, but I do not understand why.

const DELAY = 1000;

const printNumbers1 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run() {
    console.log(counter);
    counter++;

    if (counter > to) clearTimeout(timerID);

    // the function not stop the invocation without the `else` statement
    timerID = setTimeout(run, DELAY);
  }, DELAY)
}

const printNumbers2 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run() {
    console.log(counter);
    counter++;
    if (counter > to) clearTimeout(timerID);
    else {
      timerID = setTimeout(run, DELAY);
    }
  }, DELAY)
}

printNumbers1(1, 4); // continues to execute after 4th invocation
printNumbers2(1, 4); // stops execution after 4th invocation

retiving data from fetch

The JSON placeholder API gives me the data but open weather API gives error and the error is ‘Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data’
Whats going wrong? and how I can read the weather API data?


      fetch(
        // 'https://jsonplaceholder.typicode.com/posts/1'
        'api.openweathermap.org/data/2.5/weather?q=bhubneshwar&appid=2f5e9a7699ace605d4cbf50f813d7b0b'
      )
        .then((response) => response.json())
        .then((data) => console.log(data));