TypeScript/React with Web Audio API – cannot connect AudioBuffer to audio element or wavesurfer

I’m attempting to build an audio player component in a React/Next.js app with wavesurfer visualisation. My audio data is basically binary/wave audio and I have successfully been able to “play” the audio with an AudioContext and AudioBuffer.

I’ve hit 2 blockers that I haven’t made progress with despite researching similar questions:

  1. (Simple?) I cannot “connect” my AudioContext(and created audioBuffer) to a <audio /> DOM element (always shows 0s/controls disabled)
  2. I do not know how to generate an HTMLMediaElement with my audio data (audioBuffer in below code) to pass into Wavesurfer.

Note – I’ve seen similar examples which use URL.createObjectURL() – these URL’s return 404 in nextJS so I haven’t had success using this. Maybe this is the missing piece and the ways I’ve tried aren’t possible.

How do I proceed with this audio player component?

Code so far..

import { FC, useEffect, useRef, useState } from "react";
import { Box, Button, } from "@chakra-ui/react";
import { fetchAudioData } from "@/api/v1/audio";
import WaveSurfer from "wavesurfer.js";
import { AudioPlayerProps } from "./AudioPlayer.types";

export const MyAudioPlayer: FC<AudioPlayerProps> = ({}) => {
  const waveSurferRef = useRef(null);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const [audioContext, setAudioContext] = useState<AudioContext | null>(null);
  const [audioBuffer, setAudioBuffer] = useState<AudioBuffer | null>(null);
  const [wavesurfer, setWaveSurfer] = useState<WaveSurfer | null>(null);

  const setupAudio = async () => {
    const data: Uint8Array = await fetchAudioData(); // Remote call for data

    const audioCtx = new window.AudioContext();
    // Create AudioBuffer (my audio format: mono, unsigned 8-bit, 44100hz)
    const audioBuffer = audioCtx.createBuffer(
      1, // Channels (mono)
      data.length, // Number of samples
      441000 // Sample rate
    );
    const channelData = audioBuffer.getChannelData(0);
    // Copy audio data into the channel data array
    for (let i = 0; i < data.length; i++) {
      channelData[i] = data[i] / 255; // Normalize values between -1 and 1
    }
    setAudioBuffer(audioBuffer);
    setAudioContext(audioCtx);
  };

  const prepareAudioElement = () => {
    if (audioRef.current && audioContext) {
      audioContext.createMediaElementSource(audioRef.current);
      audioRef.current.controls = true;
      audioRef.current.play();
    }
  };

  const prepareWaveSurfer = () => {
    if (waveSurferRef.current && audioBuffer) {
      const ws = WaveSurfer.create({
        container: waveSurferRef.current,
        waveColor: "rgb(200, 0, 200)",
        progressColor: "rgb(100, 0, 100)",
        barWidth: 10,
        barRadius: 10,
        barGap: 2,
        // media: ?, // UNSURE HOW TO CREATE THIS WITH MY AUDIO CONTEXT
        peaks: [audioBuffer.getChannelData(0)],
        duration: 1, // Todo: populate from audio track 
        mediaControls: true,
      });
      setWaveSurfer(ws);
    }
  };
  useEffect(() => {
    prepareAudioElement();
    prepareWaveSurfer();
  }, [audioRef, audioContext, audioBuffer, waveSurferRef]);

  const playMyAudio = () => {
    if (audioRef.current && audioContext) {
      audioRef.current.play(); // DOES NOTHING

      // PLAY AUDIO IMMEDIATELY DIRECTly FROM CONTEXT
      // const source = audioContext.createBufferSource();
      // source.buffer = audioBuffer;
      // source.connect(audioContext.destination);
      // source.start();
    }
  };

  return (
    <Box w="500px">
      <div ref={waveSurferRef} />
      <audio ref={audioRef} controls />
      <Button onClick={() => setupAudio()}>Setup Audio Track</Button>
      <Button onClick={() => playMyAudio()}>Play</Button>
    </Box>
  );
};

Similar questions I’ve looked at:
React Web Audio API – Play, pause and export loaded audio file

Using AudioBuffer as a source for a HTMLAudioElement?

convert audio buffer to play as audio element

https://webaudioapi.com/samples/audio-tag/

TypeScript/React with Web Audio API errors with createMediaElementSource

How does buying code from a developer work? [closed]

I want hire a development team to build a mobile app with a admin panel for me but I have a question regarding the code I will receive.
My main question is: When the developer finishes the code, I will get the full source code for the entire project but the developer will also have a copy since they made it. Once I get the copy of code, if the developer changes their copy from their end, it won’t effect my copy of the code right?
In other words, will they have no access to my copy of the code and I can run it without issue. If code doesn’t work like this, how does it work? If you have worked with clients before, what was the delivery process like?

Thank you.

I am not a developer so my questions will be a bit naive but I want to know how the process works before I hire.

Troubleshooting WebSocket Connection Issue: Invalid Header Error When Accessing Python WebSocket Server

I’m currently developing a WebSocket server using Python. Here’s the code snippet:

import asyncio
import websockets

async def server(ws:str, path:int):
    inp = input('Client joined. Greet it. nType ')
    await ws.send(inp)
    while True:
        message = await ws.recv()
        print(f'Msg [{message}]')
        
Server = websockets.serve(server, "127.0.0.1", 8000)

asyncio.get_event_loop().run_until_complete(Server)
asyncio.get_event_loop().run_forever()

Accompanied by an HTML page (index.html):

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>Temp</h1>
    <script src="app.js"></script>
  </body>
</html>

And a JavaScript file (app.js):

function startSocket() {
  var ws = new WebSocket("ws://127.0.0.1:8000");
  ws.onopen = function (event) {
    ws.send("Sent this from client.js");
  };
}
startSocket();

Upon running the Python script and attempting to access 127.0.0.1:8000 on both Chrome and Safari, I encounter the following error message:

“Failed to open a WebSocket connection: invalid Connection header: keep-alive.

You cannot access a WebSocket server directly with a browser. You need a WebSocket client.”

I’m seeking assistance in understanding why this connection issue is occurring and how to fix it.

The code I have written is very basic, and I took it directly from the documentation. I have also searched the web for a solution, but nothing satisfactory has been found. I am looking for any pointers that would help me understand the issue and fix it.

How to evaluate arguments passed to a function using jest

I am trying to do a test,
I want to evaluate that the getCall function receives the 4 arguments,
but I don’t understand why my test is not working.

import * as getCall from './index';

test('should be called with four aguments', () =>{
    const getCallSpy = jest.spyOn( getCall, 'getCall');

    const data = {   
        method: "GET",
        url: "myUrl",
        body: "myBody",
        headers: "myHeaders"
    }
    
    expect( getCallSpy ).toHaveBeenCalledWith( {
        data
    } );

});

index.js

    import * as http from 'http';
import * as https from 'https';

export const getCall = (data: {
      method: any;
      url: any;
      body: any;
      headers: any;
    }): any => {
  
  /*more code*/
 
  }
});

How can I create a dynamic back button/page structure in remix so that the back button navigates back to the parent page?

I have a Remix app which has “loops” in it where two different parent routes lead to the same child.

main/projects/$projectSlug (this one should go back to main/projects)
main/folders/$folderId/projects -> main/projects/$projectSlug (this one should go back to folderId/projects)

A user can either navigate to a project via projects or via a folder which contains that project.
How can I create a back button that navigates to the appropriate parent route?

Problems:

  • Because I have subpages within the projectSlug page, I can’t use navigate(-1) because it only navigates back to the previous subpage instead of the parent URL

  • I have tried slicing the end off the URL but this does not take into account the different contexts

  • I have tried to use a context to save the previous state but this doesn’t work due to subpages and reloads of the same page

    My current best attempt uses a combination of path slicing and passing state down through my links but this still doesn’t take me back to the right page.

    let backPath = currentPathArray
        .slice(0, currentPathArray.length - levelsBack)
        .join("/");
    
      useEffect(() => {
        if (router?.state?.previousPath) {
          backPath = router?.state?.previousPath;
          console.log("BACK", backPath);
        } else {
          console.log("NO PATH");
        }
      }, [router]);
    
      return (
        <NavLink
          to={backPath}
        >
    

    I have checked out a lot of answers but I can’t figure out what is best for my particular case. Going forward, we will need a lot more of this kind of functionality to navigate up and down in different contexts so if anyone has pointers it would be much appreciated.

ReportValidity Shows Only On Last Input

I have a boostrap4 modal and click save button in modal will do validation checking on server. After checking, if there is errors, return errors and using setCustomValidity on every input/select with error. Lastly, use reportValidity to show all invalid popup message.

The problem is: The popup only shows for the last input/select of the errors, instead of showing for all.

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server" ClientIDMode="Static">
  <form id="form1" method="post" runat="server" novalidate>
    <table>...
    </table>

    <div class="modal fade" id="modal" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">...</div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="name" class="col-form-label">Name:</label>
                        <input type="text" class="form-control" id="name" name="name">
                    </div>
                    <div class="form-group">
                        <label for="contacts" class="col-form-label">Contacts:</label>
                        <input type="text" class="form-control" id="contacts" name="contacts">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" runat="server" onserverclick="ValidationCheck">Save</button>
                </div>
            </div>
        </div>
    </div>
  </form>
</asp:Content>
function saveAlert({data = {}}) {

    let invalidateInputs = [];
    
    setTimeout(() => {
        $("#modal").modal("show");
    },700);

    Object.entries(data.UserInfo).forEach((detail) => {
       ..repopulate modal with data
    });

    Object.entries(data.Errors).forEach((error) => {
        switch(error[0].toLowerCase()) {
            case "name":
                invalidateInputs .push(document.querySelector("#name"));
                document.querySelector("#name").setCustomValidity("Please fill in your name");
                break;
            case "contacts":
                invalidateInputs .push(document.querySelector("#contacts"));
                document.querySelector("#contacts").setCustomValidity("Please fill in your contacts.");
                break;
            default:
                break;
        }
    });

    if (invalidateInputs .length > 0) {

        // (*) even though this loops all input, the popup showed up only at last input
        invalidateInputs.forEach((input) => {
            input.reportValidity();    // -> (*)
        })
    }

    return false;
}

using System;
...

public partial class User : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ...checkuser
        Session["pagename"] = "User";
    }

    [System.Web.Services.WebMethod]
    public static string GetUser()
    {}

    protected void ValidationCheck(object sender, EventArgs e)
    {
        ValidationData result = new ValidationData();
        Errors errors = new Errors();
        errors.Name = true;
        errors.Contacts = true;

        result.UserInfo = UserDetails();

        bool showError = false;

        string userID = Request.Form["userID"] == null ? "" : Request.Form["userID"].ToString();
        ... other data from request.form

        if (checkingFoundErrors) showError = true;
        
        if (showError)
        {
            string jsFunc = string.Format("saveAlert({{ 'data': {0} }});", JsonConvert.SerializeObject(result, Formatting.None));
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
        }
        else
        {
            SaveUser_Click(this, new EventArgs());
        }
    }

    protected UserInfo UserDetails()
    {
        UserInfo result = new UserInfo();
        result.UserID= Request.Form["userID"] == null ?? "" : Request.Form["userID"].ToString();
        result.Name = Request.Form["name"] == null ?? "" : Request.Form["name"].ToString();
        result.Contacts = Request.Form["contacts"] == null ?? "" : Request.Form["name"].ToString();

        return result;
    }

    public struct UserInfo
    {
        public string UserID { get; set; }
        public string Name { get; set; }
        public string Contacts { get; set; }
    }

    public struct Errors
    {
        public bool Name { get; set; }
        public bool Contacts { get; set; }
    }

    public struct ValidationData
    {
        public UserInfo UserInfo { get; set; }
        public Errors Errors { get; set; }
    }
}

In my js file function saveAlert() at (*), when i loop through all inputs and calls reportValidity() on all inputs, how do I make all inputs with errors to be popup with its invalid message, instead of the last input.

How to use UTC time on client side?

My script works so far that the right things are shown on the website, AS long AS I am in my time zone. As soon as I change the time zone the browser shows content in the client time. Now its is crucial that things on the website are shown in my time zone time. Why is then script not working correctly?

var imgElement = document.createElement("img");

var time = new Date((new Date()).toLocaleString("en-US", {timeZone: "America/Regina"})).getHours();


 if (time >= 0 && time <= 4) {
 

How to recover and gracefully handle faild api request to a 3rd party API

I created a few functions that send requests to a 3rd party api (canvas lms) to make basic CRUD operations.

I need to add a user to a “section”. A 404 is thrown if I try to add a user to a section that doesn’t exist. In addition if I try to GET the section (before adding the user) if the section doesn’t exist the GET request will also throw a 404.

I don’t know a strategy on how to handle this sequence properly (I find myself running into this a lot with various 3rd party apis). Here is my approach:

const addUserToSection = async (sectionId, userId) => {
  try {
    await createSectionEnrollment(sectionId, userId);    
  } catch (error) {
    if (error.response.status === 404) {
      try {
        await createCanvasCourseSection({
          name: 'Section A',
          sectionId: 'sectionA',
          start: '2024-01-01',
          end: '2024-12-31',
          courseId: 5
        });
        return createSectionEnrollment(sectionId, userId);
      } catch (error) {
        console.error(error.response.message);
      }
    }
    console.error(`error message: ${error.response.message}`)
  }
};

Here are some of the functions:

const axios = require('axios');
const headers = {
  'content-type': 'application/json',
  Authorization: `Bearer API KEY HERE`
};

const baseUrl = 'https://canvas.instructure.com/api/v1'; // not a real canvas url

const createUserSectionEnrollment = async (canvasShellId, userId, notify = false) => {
  const url = `${baseUrl}/sections/${canvasShellId}/enrollments`;
  return axios({
    method: 'post',
    url,
    headers,
    data: {
      enrollment: {
        user_id: userId,
        type: 'StudentEnrollment',
        notify,
        enrollment_state: 'active',
        limit_privileges_to_course_section: true
      }
    }
  });
};

const createCourseSection = async ({ sectionName, canvasShellId, courseId }) => {
  const url = `${baseUrl}/courses/sis_course_id:${courseId}/sections`;
  return axios({
    method: 'post',
    url,
    headers,
    data: {
      course_section: {
        name: sectionName,
        sis_section_id: canvasShellId
      }
    }
  });
};

In the code above, I take the approach of trying to add a user to a section, knowing there is a chance the section doesn’t exist. If the error message is a 404, I assume (which may not be the right assumption) that the section doesn’t exist so I create the section and try again to add the user to the section.

Instead of trying to add the user directly, I could check if the section exists, but that will also throw an error if it doesn’t exist, so I’d hit the catch block either way if it didn’t exist.

Is it okay to handle and create the section in the catch block? Countless tutorials and code snippets leave comments in the catch statements that say “handle error here”, unfortunately, this isn’t basic knowledge to me and I can’t find code examples that handle errors.

If anybody can demonstrate how to handle this situation or a codebase that has these type of CRUD api requests to a 3rd party library which demonstrates how to handle errors it would be a huge help.

I want to make a snap scroll like this website, what should I use? [closed]

Berikut link website : https://marketing.neosofttech.com/presentation-english/

on this website, the scroll uses a snap but when it scrolls a lot it stays to the bottom 1 section only, and can be operated using the arrow on the keyboard.

I’ve tried using regular css with mandatory snap y and it’s not like that example website, and I tried to find the js code to do that but I haven’t found it yet.

How to get a specific array from an array of arrays?

I cannot get a single array as an output to array.some

I have tried this code:

data = [
{Surname: 'Santos', Firstname: 'Carlos'},
{Surname: 'Reyes', Firstname: 'Carla"},
{Surname: 'Michael', Firstname: 'Lebowski'}
];
var found = data.some(function(data){
return data.Surname === 'Reyes'
}
console.log(found);

The logs I get in return are:
0: {Surname: ‘Santos’, Firstname: ‘Carlos’}
1: {Surname: ‘Reyes’, Firstname: ‘Carla”}

My expected logs were:
0: {Surname: ‘Reyes, Firstname:’Carla’}

How can I get my expected logs?

When displaying a PDF inside an embed tag, is there any way to disable or remove a button from the toolbar?

I am using an embed tag to display a pdf on a webpage, and I have been trying to find a way to hide or disable the Rotate Counterclockwise button on the toolbar.

Rotate Counterclockwise button on pdf viewer toolbar

I have tried a few solutions so far, but it doesn’t seem like I am able to target the html inside the embed #document with JavaScript or CSS. I discovered I can append url parameters to the source url such as “#toolbar=0” to hide the toolbar completely, but I need to hide just one button.

How to force HTML to requesting local resource (css/js) file over HTTP instead of HTTPS?

I just created my own HTML page inside expressJS, everything looks good while running on localhost but when I upload it to my server, the HTML requesting all my local css or js file over HTTPS automatically. How do I force HTML to requesting all my local css or js using HTTP protocol?

I’ve tried to find any possible keyword and found my issue is similar to this Using HTTP version but Chrome requests HTTPS for all css and js resources but the question is not answered yet


HTML rendered from local development (localhost)

enter image description here

HTML rendered from server

enter image description here

How to get Title / Description from Facebook Reels?

I am scraping my saved Facebook reels, which is going well, but I am trying to also capture the title or description of the video to insert into the database, as well as for the filename. When I use this API: facebook-reel-and-video-downloader.p.rapidapi.com, I don’t get the info.

When I try to use Ajax and go straight to the page, I don’t get anything. Any ideas how to capture that info?

https://www.facebook.com/reel/104244076084135