How to cut audiofile from input in browser with js, lamejs?

I have input in my Vue component where i upload audiofile via @change, next i need to cut it, for example i have 30 seconds audio and i need to receive audio from 5 to 15 second.
I have installed lamejs package to do that.

But after all my operations with audio i receive cutted audio but without any sound, so i dont know where is the reason of that. Need help!

method which upload file

async onUploadFile(event) {
        const fileData = event.target.files[0];
        this.file = fileData;
        await this.decodeFile(fileData);
    },

method which decodes file to audioBuffer

async onUploadFile(event) {
        const fileData = event.target.files[0];
        this.file = fileData;
        await this.decodeFile(fileData);
    },

method which cut audio and encode it to mp3 and then receive blob url

async audioBufferSlice(buffer, begin, end) {
        const audioContext = new AudioContext();
        const channels = buffer.numberOfChannels;
        const rate = buffer.sampleRate;
        const duration = buffer.duration;

        const startOffset = rate * begin;
        const endOffset = rate * end;
        const frameCount = endOffset - startOffset;

        const audioLength = endOffset - startOffset;

        let trimmedAudio = audioContext.createBuffer(
            buffer.numberOfChannels,
            audioLength,
            rate
        );

        for(var i = 0; i < buffer.numberOfChannels; i++){
            trimmedAudio.copyToChannel(buffer.getChannelData(i).slice(begin, end), i);
        }

        var audioData = this.serializeAudioBuffer(trimmedAudio);

        let mp3Data = [];
        const sampleBlockSize = 1152;

        let mp3encoder = new lamejs.Mp3Encoder(2, audioData.sampleRate, 128);

        var left = new Int8Array(audioData.channels[0].length);
        var right = new Int8Array(audioData.channels[1].length);

        for (var i = 0; i < audioData.channels[0].length; i += sampleBlockSize) {
            var leftChunk = left.subarray(i, i + sampleBlockSize);
            var rightChunk = right.subarray(i, i + sampleBlockSize);
            var mp3buf = await mp3encoder.encodeBuffer(leftChunk, rightChunk);
            if (mp3buf.length > 0) {
                mp3Data.push(mp3buf);
            }
        }

        let buf = await mp3encoder.flush();

        if (buf.length > 0) {
            mp3Data.push(buf);
        }

        var blob = new Blob(mp3Data, {type: 'audio/mp3'});
        var url = window.URL.createObjectURL(blob);
        console.log('MP3 URl: ', url);
    },

What did I do wrong that I receive cut audio but without any sound?
I look at that repository as example https://github.com/Vinit-Dantkale/AudioFy

Beer bottle game

Beer Bottles Game Development in JAVA LANGUAGE.
Beer Bottles Game Development Preamble:

  1. In this game, there are 21 Beer bottles and 2 players You and Computer.
  2. You and Computer would pick up the Beer bottles one by one.
  3. At a time, any number of beer bottles can be picked up between 1 and 4 (inclusive)
  4. The one, who will have to pick up the last bottle, is the loser and will have to pay the bill, Design and implement a game, making use of Artificially Intelligent algorithm, so that if is playing first, then the Computer would pick up the bottles intelligently each time, Computer would always Win. The Computer would never Lose.

Javascript Google Auth Error redirect_uri: storagerelay://blob/?id=

I am trying to get Google Auth working. The Auth is being called from an IFrame embedded on a website. The code looks as such:

const client = google.accounts.oauth2.initCodeClient({
    client_id: 'xxxxxx',
    scope: 'https://www.googleapis.com/auth/calendar.readonly',
    ux_mode: 'popup',
    callback: (response) => {
    
  },
});

function signIn() {
    client.requestCode();
}

With the html being very simple:

<a class="btn btn-primary" onclick="signIn()"><i class="fab fa-google"></i> Sign-In With Google</a>

When the button is clicked, the following is returned.

enter image description here

What could be causing this the storage issue?

Run javascript code on multiple pages of a multi-page website

I am building a google chrome extension to automate a task that requires navigation to different pages on a multi-page website. Let say on the first page there’s a button which navigates to another page on the same website, I am using javascript to click on that button so that it navigates to the desired page but after successful navigation from the first page the javascript code which I wrote for navigated page doesn’t work.

How can I make it work and again do some tasks using javascript on the navigated page?

How do you modify an object multiple times and return it in a spread operator?

I’m working in React. I’m using useState to hold an object in state. To make one change to the object and return it I can use the spread operator like so …

 const [formWizard, setFormWizard] = useState(FORM_CONTROLS.steps[index]);

...

 const addSection = section => {
...

   setFormWizard(wizard => ({
     ...wizard,
     wizard: formWizard.controls[14].group.push(...subjectAddressCopy.slice(0, 5))
   }));
}

But what if I need to make multiple changes? I’ve tried putting a comma between them, use &&, and wrapping it in an object (though I think that would change the data structure). In either event known of those things worked.

   setFormWizard(wizard => ({
      ...wizard,
      wizard: formWizard.controls[14].group.push(...subjectAddressCopy.slice(0, 5),
      formWizard.controls[14].trash) // how can I also make this change?
   }));

How can I make two changes to formWizard and return it?

Vue 3 Automatic Update Array Outside Vue App

I have a simple scoring app that uses Vue 3 to maintain the scores and totals. I have a global teams object that contains all the scores. My Vue 3 app updates my scores quite happily within itself, but I also need to access the teams object outside of the Vue app to do other non-user interface activities, like saving etc. and i’d like to keep them sync’d.

My global teams object looks like this:

let teams = [];
teams[0] = {
    players: [
      { name: "Player 1" },
      { name: "Player 2" }
    ],
    scores: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  };
teams[1] = {
    players: [
      { name: "Player 1" },
      { name: "Player 2" }
    ],
    scores: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  };

I link it to my Vue 3 app like this:

data() {
      return {
        home: teams[0],
        away: teams[1]
      };
    },

If I update a score on the home or away object within Vue, the global teams object is not updated. For example I have a Save function (outside of Vue) that relies on the teams object be kept in sync with updates to home and away.

Is there a way to do this? Am I going about it all wrong? I could move my Save function into Vue but I was trying to separate out my user interface logic. I do have other functions that need access to a sync’d teams object and i’d rather not add everything into the Vue app.

Thanks in advance. J.

dynamic Employee table and how to css style

I wanted to dynamically create an employee table from a dataset. And I wanted to figure out how to bold all the department names, or supervisors. Here is a sample of my code:

var data = [{"name": "John Smith", "primary": 1, "title": "CEO", "phone":123}, {"name":"Frank Beans", "title": "COO", "phone": 333}, {"name": "test", "title": " newemployee", "phone": 555}, {"name": "Damar", "primary": 1, "title": "supervisor of quality", "phone": 999}]

function buildTable(data){
var table = document.getElementById(‘mytable’)

for(var i =0; i < data.length; i++){
    var row = `
    <tr>
        <td data-id="primary">${data[i].name}</td>
        <td>${data[i].title}</td>
        <td>${data[i].phone}</td>
    </tr>`
    table.innerHTML += row
}

}

I am able to display the table, which is great! But, when I try to bold the td cell that has name it bolds both cells of John Smith and Frank Beans. I would like to bold John Smith and Damar since John is the CEO and Damar is a supervisor. I was thinking of looping through the data and if it has primary === 1 then i could apply the bold to the cell but couldn’t figure out how to do that. I have been stuck on this for a few hours and need some help.

Axios forward slash (/) url encoding issue

I am having a technical difficulties since I have to change date formats from ‘YYYYMMDD’ to ‘MM/DD/YYYY’.

I am using Axios; then Axios automatically encode my request uri.

For example, I made codes to create a request: STARTDATE=04/01/2021&ENDDATE=04/30/2021
but then when it sends through Axios it becomes: STARTDATE=04%2F01%2F2021&ENDDATE=04%2F30%2F2021; Because ‘/’ is encoded to ‘%2F’ automatically.

The requesting url I want to send is = 04/01/2021, != 04%2F01%2F2021
Any insights will be appreciated!

Website dark mode change triggers video source change

I have a custom button in my WordPress Elementor page that randomly changes the video playing on the website. The URLs are defined in the back end, and the PHP code is added in the footer. Not much to it, seems to work well:

<?php
$all_random_urls = array();
if( have_rows('videor_random_url') ):

    while( have_rows('videor_random_url') ) : the_row();

        $sub_value = get_sub_field('add_videor_random_url');
        $all_random_urls[] = $sub_value;
        
    endwhile;

else :
    // Do something...
endif;
?>
<script>
    jQuery(document).ready(function() {
        var all_datas = "";
        var new_video_url = "";
        setTimeout(function() {
            all_datas = <?php echo json_encode($all_random_urls); ?>;
            
            jQuery('#random_video_changer').on('click', function() {
                var present_video_url = all_datas[Math.floor(Math.random() * all_datas.length)];
                if(new_video_url != '' && new_video_url == present_video_url) {
                    present_video_url = all_datas[Math.floor(Math.random() * all_datas.length)];                    
                    new_video_url = present_video_url;
                    jQuery('.mdp-videor-video video.elementor-video').attr('src', new_video_url);
                } else {
                    new_video_url = present_video_url;
                    jQuery('.mdp-videor-video video.elementor-video').attr('src', new_video_url);   
                }
            });
        }, 2000);
        
    });
</script>

What I am trying to do now is use the dark mode toggle button from my Darklup plugin to change the video playing. I have managed to do it by changing the on-click from ‘#random_video_changer’ to whatever the div id/class of the button is. This works but in this way it is impossible to use different videos for dark and light theme since every button click toggles a video change. I have been trying to change the following plugin js to call for video change when theme is dark or light, but I am struggling to get any results.

    darkModeSwitchEvent: function() {

            let $that = this;

            $(this.switchTrigger).on( 'click', function(e) {

                let $this = $(this);

                $('html').toggleClass($that.darkEnabledClass);

                // Storage data
                if( $this.is(':checked') ) {
                    localStorage.setItem("darklupModeEnabled", $that.darkEnabledClass);
                    localStorage.setItem("triggerCheked", "checked");
                    $this.closest('.darkluplite-mode-switcher').addClass('darkluplite-dark-ignore');

                    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
                        localStorage.removeItem("lightOnOSDarkCheked");
                    }
                } else {
                    $this.closest('.darkluplite-mode-switcher').removeClass('darkluplite-dark-ignore');
                    localStorage.removeItem("darklupModeEnabled");
                    localStorage.removeItem("triggerCheked");

                    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
                        localStorage.setItem("lightOnOSDarkCheked", true);
                    }
                }

            } )

What would be the simplest way to achieve this – when light mode is active the video is played from video array 1, when dark mode is active, video is played from video array 2?

I am trying to learn how to do this on my own but have spent few hours on this now without any movement in the right direction, so any help is greatly appreciated.

How could I automatically read all of the directories and add all files that end in .js to discord collection

This is the code I currently have, how would adapt this to check each sub-directory:

const fs = require('fs')

module.exports = (client, Discord) =>{
    const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'))

    for(const file of command_files){
            const command = require(`../commands/${file}`);
            if(command.name) {
                client.commands.set(command.name, command);
            } else {
                continue
            }
         }
}

And this is the layout I have for the commands folder the folder layout

How to code “re-run custom function” button in Google Sheet custom function?

I’m having the problem lots are having where my Apps Script code on Gsheets doesn’t automatically update unless it registers a change in the parameters. The custom function I’m using counts the number of cells that are highlighted a specific color. Changing the color of a cell doesn’t re-run the script. I wanted to add a check box in a cell and every time I click it, it reruns the function.

function COUNTCOLOR(countRange,colorRef,recalc) {
  var activeRg = SpreadsheetApp.getActiveRange();
  var activeSht = SpreadsheetApp.getActiveSheet();
  var activeformula = activeRg.getFormula();
  var countRangeAddress = activeformula.match(/((.*),/).pop().trim();
  var backGrounds = activeSht.getRange(countRangeAddress).getBackgrounds();
  var colorRefAddress = activeformula.match(/,(.*))/).pop().trim();
  var BackGround = activeSht.getRange(colorRefAddress).getBackground();
  var countCells = 0;
  for (var i = 0; i < backGrounds.length; i++)
    for (var k = 0; k < backGrounds[i].length; k++)
      if ( backGrounds[i][k] == BackGround )
        countCells = countCells + 1;
  return countCells;
};

The function works, but only without the “recalc” variable, which is the variable I need to add a check box to re-run the code. I get an error: “Range not found (line 6)”. Any advice on getting this to work?

Thanks!

Need Help JavaScript Challenge

I can’t seem to pass the test for this challenge.

// Write a function that takes 6 values (a,b,c,d,e,f) as arguments
// Sum a and b
// Then substract by c
// Then multiply by d and divide by e
// Finally raise to the power of f and return the result
// Tipp: mind the order

function myFunction(a, b, c, d, e, f) {

    return 
}

Script dynamically inserted later on: how to make it run?

In my React app, I have scripts that are inserted dynamically later on. The scripts don’t load.

A field called content in my database for example contains data such as the following:

<p>Some text and html</p>
<div id="xxx_hype_container" style="width: 46px; height: 50px; overflow: hidden;">
<script type="text/javascript" charset="utf-8" src="https://example.com/uploads/hype_generated_script.js?499892"></script>
</div>
<div style="display: none;" aria-hidden="true"> 
<div>Some text.</div> 
Etc…

In my React app, I call on this db field to display that content:

import { thePost } from "../../../appRedux/actions/postAction";

class Post extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            post: "",
        };
    }

    componentDidMount() {
        // get post data from db
        this.props.thePost(this.props.match.params.postId);
    }

    render() {
        return (
            <div className="container">
                {post.content}
            </div>
        )
    }
}

It correctly loads the data from the database and displays the html from that data. But the data also contains a script, which does NOT get loaded. I think the script doesn’t work because it is dynamically inserted later on. How can I make this script work/run?

This post suggest a solution for dynamically inserted scripts, but I don’t think I can apply this solution because in my case the script/code is loaded from a database (so how to then use nodeScriptReplace on the code…?). Any suggestions how I might make my scripts work?