Discord.js not playing sound

I have been trying all day to write a simple bit of code that makes a Discord Bot join a channel and then play a sound. But for some reason I can’t seem to get it to work. I have tried many different things but it just doens’t play the sound. I also get no error or anything. Could somebody explain to me what I am doing wrong? The code can be found below.

const Discord = require("discord.js");
const discordTTS = require('discord-tts');
const { Client, GatewayIntentBits } = require('discord.js');
const { joinVoiceChannel } = require('@discordjs/voice');
const { createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const { createAudioResource } = require('@discordjs/voice');
const { join } = require('node:path');
const { AudioPlayerStatus } = require('@discordjs/voice');

const player = createAudioPlayer({
  behaviors: {
    noSubscriber: NoSubscriberBehavior.Pause,
  },
});

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});

client.on('ready', (c) => {
  console.log(c.user.tag + " is online!");
});

client.on('messageCreate', (message) => {
  if (message.content === 'hello') {
    const connection = joinVoiceChannel({
      channelId: message.member.voice.channel.id,
      guildId: message.member.voice.guild.id,
      adapterCreator: message.member.voice.guild.voiceAdapterCreator,
      selfDeaf: false,
    });
    const player = createAudioPlayer();
    connection.subscribe(player);
    resource = createAudioResource('/sounds/alert.mp3');
    player.play(resource);
  }
});

It joins the channel fine but then doens’t play the sound. I double checked and the file (alert.mp3) is in the sounds folder.

Issue Passing Size Parameter from JavaScript to Django Backend

I’m encountering an issue with passing the “size” parameter from my JavaScript function to my Django backend. Here’s the relevant code snippet from my Django view:

def get_product(request, slug):
    try:
        product = Product.objects.get(slug=slug)

        if request.GET.get('size'):
            size = request.GET.get('size')
            print(size)

        return render(request, "core/product_detail.html")

    except Exception as e:
        print(e)

And here’s the JavaScript function:

function get_correct_price(size) {
    console.log(size);
    window.location.href = window.location.pathname + `?size=${size}`;
}

In my HTML template, I’m calling the JavaScript function with the size parameter:

<button onclick="get_correct_price('{{ s.name }}')">{{ s.name }}</button>

However, when I click the button, the size parameter doesn’t seem to be passed to the backend. I’ve verified that the JavaScript function is being called, and the size parameter is logged correctly in the console.

Could you please help me identify why the size parameter is not being received in the backend? Any insights or suggestions would be greatly appreciated. Thank you!

Firefox extension background script terminated preemptively

I have a Firefox extension that for certain pages listens to the webRequest.onHeadersReceived for specific URLs that it opens in order to remove the “content-disposition” header when it contains “attachment”. That way some content is shown in the browser rather than downloaded as a file.

When the extension opens the URL in a new tab, it works fine; the listener is called and I can modify the headers. But, if I instead open the URL in the currently active tab, it seems the background script gets terminated and the listener is never called.

Is there a way to prevent the background script from terminating, or am I doing something wrong to cause this?

From a content script a message is sent containing a URL, e.g. for an image, to open. The background script:

// background.ts

browser.runtime.onMessage.addListener(handleMessage);

function handleMessage(message: IMessage, sender: browser.runtime.MessageSender, sendResponse: (response?: any) => void) {
    const command = message.command;
    switch (command) {
        case "OPEN_IMAGE": {
            const { url, focusTab, newTab } = message.data;
            return openImage(url, focusTab, newTab);
        }
        // other cases...
    }
}

async function openImage(url: string, shouldFocus: boolean, newTab: boolean) {
    let tab: browser.tabs.Tab;

    if (newTab) {
        // This branch works as expected. The URL is loaded (below) and the image
        // is shown rather than downloaded as a file.
        tab = await browser.tabs.create({ active: shouldFocus });
    }
    else {
        // Using this tab to load the URL into doesn't work. The image is downloaded
        // as a file, rather than shown in the tab.
        const activeTabs = await browser.tabs.query({ active: true, currentWindow: true });
        tab = activeTabs[0];
    }

    requestHandler.startListening(url);
    await browser.tabs.update(tab.id!, { url, loadReplace: newTab });
}

Inside requestHandler.startListening this is what happens:

class RequestHandler {
    private readonly _urlsToListenFor: string[] = [];

    public startListening = (url: string) => {
        console.log("added");
        this._urlsToListenFor.push(url);

        // I've already checked no listener is added before this
        browser.webRequest.onHeadersReceived.addListener(
            this.onHeadersReceived,
            {
                urls: ["*://*/*"],
                types: ["main_frame"]
            },
            ["responseHeaders", "blocking"]);
    };

    private onHeadersReceived = (details: browser.webRequest._OnHeadersReceivedDetails) => {
        const listenerIndex = this._urlsToListenFor.indexOf(details.url);
        if (listenerIndex === -1) return;
    
        console.log("removed");
        this._urlsToListenFor.splice(listenerIndex, 1);
    
        return this.getBlockingResponse(details);
    };

    private getBlockingResponse = (details: browser.webRequest._OnHeadersReceivedDetails) => {
        // Make sure the image is opened in the browser rather than downloaded
        const contentDispIndex = details.responseHeaders
            ?.findIndex(h => h.name.toLowerCase() === "content-disposition" &&
                             h.value!.toLowerCase().startsWith("attachment"));
    
        return {
            responseHeaders: details.responseHeaders!
                .filter((_, index) => index !== contentDispIndex)
        };
    };
}

console.log("new RequestHandler");
export default new RequestHandler();

Given the console.log statements, this is what I see in the console:

// newTab === true
added
removed

// newTab === false
added
new RequestHandler

Items are being added in the cart in multiples of 3 in Django

I am creating a ecommerce website on Django but the problem is that when I add a item in the cart the quantity is set to 3 instead of 1. and when I increase the quantity by clicking one more time. It’s quantity becomes 6 instead of 2 and so on.

Below is the code from cart.html to add and remove items from the cart.

                    <div class="li-cartstyle cartbodyinformation-quantity">
                        <p class="quantity-input">{{item.quantity}}</p>
                        <div class="cartquantity-buttons">
                            <i data-product={{item.product.id}} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i>
                            <i data-product={{item.product.id}} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i>
                        </div>
                    </div>

and below is the code from cart.js

                    var updateBtns = document.getElementsByClassName('update-cart')

                var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser';

                for(var i=0; i < updateBtns.length; i++){
                    updateBtns[i].addEventListener('click', function(){
                        var productId = this.dataset.product
                        var action = this.dataset.action
                        console.log('productId:', productId, 'naction: ', action)

                        console.log('USER: ',user)

                        if(user === 'AnonymousUser'){
                            addCookieItem(productId, action)
                        }
                        else{
                            updateUserOrder(productId, action)
                        }
                    })
                }

                function addCookieItem(productId, action){
                    console.log('Not Logged in')

                    if (action == 'add'){
                        if (cart[productId] == undefined){
                            cart[productId] = {'quantity': 1}
                        }
                        else {
                            cart[productId]['quantity'] += 1
                        }
                    }

                    if (action == 'remove'){
                        cart[productId]['quantity'] -= 1

                        if (cart[productId]['quantity'] <= 0){
                            console.log('Remove Item')
                            delete cart[productId]
                        }
                    }

                    console.log('Cart:', cart)
                    document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
                    location.reload()
                }


                function updateUserOrder(productId, action){
                    console.log('User is logged in, sending data..')

                    var url = '/update_item/'

                    fetch(url, {
                        method:'POST',
                        headers:{
                            'Content-Type':'application/json',
                            'X-CSRFToken': csrftoken,
                        },
                        body:JSON.stringify({'productId': productId, 'action': action  })
                    })

                    .then((response) => {
                        return response.json()
                    })

                    .then((data) => {
                        console.log('data:', data)
                        location.reload()
                    })
                }

and below is my views.py

def cart(request):
    data = cartData(request)
    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    context = {'items':items, 'order':order, 'cartItems':cartItems}
    return render(request, 'store/cart.html', context)

def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']

print('Action:', action)
print('productId:', productId)


customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)

orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

if action == 'add':
    orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
    orderItem.quantity = (orderItem.quantity - 1)

orderItem.save()

if orderItem.quantity <= 0:
    orderItem.delete()

return JsonResponse('Item was added', safe=False)

rendering charts with javascript in flask

my task here is to create dynamic chart with help of python/flask and html/javascript, so idea is that customer is writting comments on some product and my task is to collect those comments, classify it by transformer model and build statistical analysis system, which will build chart on the base of data
Finnally on the based of following site : chart on web page

i have changed my code according following line :

import numpy as np
from flask import Flask,request,jsonify,render_template
import pickle
from transformers import pipeline
from collections import Counter
import matplotlib.pyplot as plt
sentiment_pipeline = pipeline("sentiment-analysis")
app =Flask(__name__)
# @app.route('/')
def home():
    return render_template("Commenting.html")

@app.route('/predict',methods=['POST'])
def predict():
    text =  [x for x in request.form.values()]
    status = []
    for sentence in text:
        status.append(sentiment_pipeline(sentence)[0]['label'])
    data = Counter(status)
    data ={"Positive":list(data.values())[0],"Negative":list(data.values())[1]}
    positive_text =list(data .keys())[0]
    positive_frequency =list(data .values())[0]
    negative_text = list(data.keys())[1]
    negative_frequency = list(data.values())[1]
    total =positive_frequency+negative_frequency
    text_sho =(f'{positive_text}  takes {positive_frequency/(positive_frequency+negative_frequency)*100 } % '
               f'and {negative_text} takes {negative_frequency/(positive_frequency+negative_frequency)*100} %')

    # sentiment_pipeline = pipeline("sentiment-analysis")
    # status = []
    # for sentence in text:
    #     status.append(sentiment_pipeline(sentence)[0]['label'])
    #     # print(sentiment_pipeline(sentence)[0])
    # emotion_counter = Counter(status)
    # plt.pie([float(v) for v in emotion_counter.values()], labels=[k for k in emotion_counter],
    #         autopct="%2.3f%%")
    # plt.savefig("templates/sentiment_distribution.png")
    # plt.show()
    # values =[float(v) for v in emotion_counter.values()]
    # labels = [k for k in emotion_counter]
    #

    # text=list(text)
    return render_template('templates/Commenting.html', prediction_text=text_sho,data=data)
    # sentiment_pipeline = pipeline("sentiment-analysis")
    # result =sentiment_pipeline(text)[0]
    # if result['label']=='POSITIVE':
    #     return render_template('Commenting.html',prediction_text=f'emotion of comment is positive')
    # else:
    #     return render_template('Commenting.html', prediction_text=f'emotion of comment is not positive')
if __name__ =="__main__":
    app.run()

and html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sell Weapons</title>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load("current", {packages:["corechart"]});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
            {% for key, value in data.items() %}
                {% if value is string %}
                    ['{{ key }}', '{{ value }}'],
                {% else %}
                    ['{{ key }}', {{ value }}],
                {% endif %}
            {% endfor %}
        ]);

        var options = {
          title: 'Clients comments',
          is3D: true,
          //pieHole: 0.5
          pieStartAngle: 100
          /*slices: {
            2: {offset: 0.2},
            3: {offset: 0.3}
          }*/
          /*slices: {
            1: { color: 'transparent' }
          }*/
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      }
    </script>
</head>
<body>
<form action="{{ url_for('predict')}}"method="post">
    <label for="comment1">evaluate first product</label><br>
    <input type="text" id="comment1" name="comment1" required="required"><br>
      <label for="comment2">evaluate second product</label><br>
    <input type="text" id="comment2" name="comment2" required="required"><br>
      <label for="comment">evaluate third product</label><br>
    <input type="text" id="comment" name="comment3" required="required"><br>
     <input type="submit" value="Submit">
</form>

 <h4 style="color:Violet;">
   {{ prediction_text }} </h4>

<h2>customer satisfaction</h2>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>

</body>
</html>

but when i am running code, i am getting following mistake :

Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

please someone with higer experience help me to fix this simple task

Value of a variable remains unaltered when assigned during a loop

I think the answer to question may lie here, but I can’t understand the answer.

The value of searchedItem remains unaltered. The following is my pseudocode.

try {
  let searchedItem = 'literallyAnything'
  const allCollections; // get all collections from a mongoDB
  
  foreach allCollections () {
    foreach childOfEachCollection () {
      foreach childOfPreviousChild () {
        if (currentChild.id == requestedId) {
          searchedItem = currentChild
          // if I do a console.log(searchItem) here I get the desired result
        }
      }
    }
  }
// but if I do a console.log(searchItem) here I get "literallyAnything"; shouldn't I be getting my desired (and now mutated inside the for loop) result ?
res.status(200).json(searchedItem) // I wish to send this to frontend 
}
catch (error) { console.log(error) }

So, as mentioned above I read this answer, but I don’t understand it.

To tackle the above, I decided to create another method whose sole job would be to send response to the frontend. And I decided to call it from the if statement itself, where I know the value of searchedItem still exists, which worked upto an extent. What I mean by that is, I do get the desired output in my browser, but additionally I also get the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, and my server crashes. I’m truncating the code for sake of brevity.

// The new method that I created
const sendResponse = (response, statusCode, data) => response.status(statusCode).json(data)
// Including only the modified if statement
if (currentChild.id == requestedId) {
  searchedItem = currentChild
  sendResponse(res, 200, searchedItem)
}

What change should I implement in my code?
Thank you.

onInput changes editablediv behavior, moving the cursor to first index every time onInput is invoked

<div className="min-w-[600px] min-h-[36.8px]" >
                 <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} >
                  {Object.values(item)}
              </div>

When I use this code above for editable-div, when onInput is triggered, the index keeps on moving to the front. E.g. when I type ‘fruit’ it becomes ‘tiurf’

 <div className="min-w-[600px] min-h-[36.8px]" >
                 <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={() => onChange} >
                  {Object.values(item)}
              </div>

I used this code before, which worked. And I went and did some other things completely unrelated to the code, and a day after it didn’t work.

const onChange = (e: any) => {
    console.log(1)
    let targetId = e.currentTarget.id
    let objectContent = e.currentTarget.textContent
    let checkIndex = parseInt(targetId.split('-')[2])
    let checkTitle = targetId.split('-')[1]
    let newArr = [...content]
    newArr[checkIndex][checkTitle] = objectContent
    setContent(newArr)
    updateData(content)
  } 

This is the onChange function that is being triggered.

It works as usual when onInput is not triggered, and when it is triggered, it starts moving the cursor to the front. What I want is to store the value inside the div, in a state to furthur edit and write inside of it.

sqlite3 not locating the bindings.js foulder

ome/container/node_modules/bindings/bindings.js:135
throw err;
^
Error: Could not locate the bindings file. Tried:
→ /home/container/node_modules/better-sqlite3/build/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/build/Debug/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/build/Release/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/out/Debug/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/Debug/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/out/Release/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/Release/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/build/default/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/compiled/16.20.2/linux/x64/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/addon-build/release/install-root/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/addon-build/debug/install-root/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/addon-build/default/install-root/better_sqlite3.node
→ /home/container/node_modules/better-sqlite3/lib/binding/node-v93-linux-x64/better_sqlite3.node
at bindings (/home/container/node_modules/bindings/bindings.js:126:9)
at new Database (/home/container/node_modules/better-sqlite3/lib/database.js:48:64)
at new Enmap (/home/container/node_modules/enmap/src/index.js:152:18)
at Object. (/home/container/utils.js:1:7912)
at Module._compile (node:internal/modules/cjs/loader:1198:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1252:10)
at Module.load (node:internal/modules/cjs/loader:1076:32)
at Function.Module._load (node:internal/modules/cjs/loader:911:12)
at Module.require (node:internal/modules/cjs/loader:1100:19)
at require (node:internal/modules/cjs/helpers:119:18) {
tries: [
‘/home/container/node_modules/better-sqlite3/build/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/build/Debug/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/build/Release/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/out/Debug/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/Debug/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/out/Release/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/Release/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/build/default/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/compiled/16.20.2/linux/x64/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/addon-build/release/install-root/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/addon-build/debug/install-root/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/addon-build/default/install-root/better_sqlite3.node’,
‘/home/container/node_modules/better-sqlite3/lib/binding/node-v93-linux-x64/better_sqlite3.node’
]
}

the bindings.js is on node modules with all stuffs

Solana Cannot read properties of null (Tobuffer) error

I’m trying to create an SPL token, but I get this error: TypeError: Cannot read properties of null (reading ‘toBuffer’). This means that the mintkeypair.public key is null, but how is that possible? The mintkeypair.publickey is generated in the code.

This is the code:

console.log("ismutable :", isMutable, "and revoke", revokeMint, "revoke free", revokeFreezeAuth)

      const lamports = await getMinimumBalanceForRentExemptMint(connection)
      const mintKeypair = Keypair.generate()
      const tokenATA = await getAssociatedTokenAddress(
        mintKeypair.publicKey,
        publicKey
      )
      console.log("mintKeypair.publicKey:", mintKeypair.publicKey);

      const createMetadataInstruction = createCreateMetadataAccountV3Instruction(
        {
          metadata: PublicKey.findProgramAddressSync(
            [
              Buffer.from("metadata"),
              TOKEN_PROGRAM_ID.toBuffer(),
              mintKeypair.publicKey.toBuffer()
            ],
            TOKEN_PROGRAM_ID
          )[0],
          mint: mintKeypair.publicKey,
          mintAuthority: publicKey,
          payer: publicKey,
          updateAuthority: publicKey

        },
        {
          createMetadataAccountArgsV3: {
            data: {
              name: form.tokenName,
              symbol: form.symbol,
              uri: `${ipfsurl}`,
              description: form.description,
              creators: null,
              sellerFeeBasisPoints: null,
              uses: null,
              collection: null
            },
            isMutable: isMutable,
            collectionDetails: null
          }
        }
      )

      const createNewTokenTransaction = new Transaction().add(
        SystemProgram.createAccount({
          fromPubkey: publicKey,
          newAccountPubkey: mintKeypair.publicKey,
          space: MINT_SIZE,
          lamports: lamports,
          programId: TOKEN_PROGRAM_ID
        }),
        createInitializeMintInstruction(
          mintKeypair.publicKey,
          form.decimals,
          revokeMint ? null : publicKey,
          revokeFreezeAuth ? null : publicKey,
          TOKEN_PROGRAM_ID
        ),
        createAssociatedTokenAccountInstruction(
          publicKey,
          tokenATA,
          publicKey,
          mintKeypair.publicKey
        ),
        createMintToInstruction(
          mintKeypair.publicKey,
          tokenATA,
          publicKey,
          form.amount * Math.pow(10, form.decimals)
        ),
        createMetadataInstruction
      );

The fix this error, i followed some tutorials on youtube but it’s seems that i cannot fix this issue :C

Why does devextreme customstore ask for a method that is already implemented?

I’m using devextreme vue, I’m trying to implement asynchronous loading in a select component.
I create a customstore like this

  const loadDataSource = (searchValue: string) => {
if (!asyncSettings.value) return
const asyncFunction = asyncSettings.value.asyncFunction
const asyncName = "asyncName"
if (isAsyncComponent && dataSource) {
  dataSource.value = new DataSource({
    store: new CustomStore({
      key: asyncName,
      loadMode: "raw",
      load: async () => {
        isLoaded.value = false
        const dataSource = await asyncFunction(searchValue)
        selectElement.value.instance.field().value = searchValue
        activePlacehodler.value = ""
        return dataSource
      },
      byKey: async function (key) {
        return new Promise(resolve => resolve("succses"))
      },
    }),
  })
}
}

I’m adding a function that does asynchronous loading of elements.
But I keep getting the following error

Uncaught (in promise) Error: E4011 - Custom Store method is not implemented or is not a function: byKey. See:
http://js.devexpress.com/error/23_1/E4011

This error asks to install the byKey method, which is already implemented

How do you decide which tools to invest in for your business? [closed]

I’m seeking advice on the criteria and strategies for selecting the most beneficial tools for my business needs while considering factors like cost, functionality, scalability, and alignment with business goals.

I’ve researched different business management tools, read reviews, and consulted with peers in similar industries to gather insights on their experiences with various solutions. I expected to find a more structured approach or framework for evaluating and prioritizing business tool investments, considering factors like cost-effectiveness, scalability, ease of integration, and alignment with our business objectives.

Failed to open for writing:java to filenotfoundException faield:EACCES(permission denied)

FileNotFoundException: open failed: EACCES (Permission denied)Failed to open for writing:java to filenotfoundException faield:EACCES(permission denied)

FileNotFoundException: open failed: EACCES (Permission denied)

In emulator (i use genymotion) it works fine, but when I run it on a real device (my phone is ASUS ZenFone Laser 5.0) throws a filenotfoundexception java.io.FileNotFoundException: /storage/emulated/0/cam20160926_075819.jpg: open failed: EACCES (Permission denied) imgBitmap = …

Webpack outputting too many files

Here is my webpack file:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  entry: {
    index: './src/js/index.es6.js', // Entry point of your application
    edit: './src/scss/edit.scss',
    style: './src/scss/style.scss'
  },
  mode: 'development', // or 'production'
  output: {
    filename: '[name].js', // Use [name] placeholder to generate unique filenames
    path: path.resolve(__dirname, 'dist') // Output directory
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        test: /.svg$/,
        loader: 'file-loader' // or any other loader you want to use for SVG files
      },
      {
        test: /.scss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '../' // Adjust the public path for CSS files
            }
          },
          'css-loader',   // Turn CSS into CommonJS
          'sass-loader'   // Compile Sass to CSS
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: (pathData) => {
        // Use entry point name for CSS filenames
        return pathData.chunk.name === 'index' ? 'index.css' : `${pathData.chunk.name}.css`;
      }
    })
  ],
  devtool: 'source-map' // Generate CSS source maps
};

Here is my file structure:

  • /src/js/index.es6.js
  • /src/scss/edit.scss
  • /src/scss/style.scss

I want to out just the following files:

  • /dist/index.js
  • /dist/edit.css
  • /dist/style.css

But instead I’m getting additional files:

  • /dist/index.css
  • /dist/edit.js
  • /dist/style.js

Unable to decode audio data and get sample rate

I am trying to get the sample rate of each chunk of audio recorded using AudioContext but when I run my current code it prints the sample rate once and then keeps printing Uncaught (in promise) DOMException: Failed to execute 'decodeAudioData' on 'BaseAudioContext': Unable to decode audio data. Why is this occurring and how can I fix it?

async function getSampleRate() {
  try {
    const constraints = {
      audio: {
        channelCount: 1
      }
    };
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    mediaRecorder = new MediaRecorder(stream, {
      mimeType: 'audio/webm'
    });

    // Start recording audio
    mediaRecorder.start(1000);

    // Create an AudioContext object
    const audioContext = new(window.AudioContext || window.webkitAudioContext)();

    // Function to handle data available
    const handleDataAvailable = async(e) => {

      // Create a Blob from the received audio data
      const audioBlob = new Blob([e.data], {
        type: 'audio/webm'
      });

      // Create a URL for the Blob
      const audioURL = URL.createObjectURL(audioBlob);

      // Fetch the audio data as an ArrayBuffer
      const response = await fetch(audioURL);
      const audioArrayBuffer = await response.arrayBuffer();

      // Decode the ArrayBuffer into an AudioBuffer
      const audioBuffer = await audioContext.decodeAudioData(audioArrayBuffer);

      // Extract the sample rate
      const sampleRate = audioBuffer.sampleRate;

      // Log the sample rate
      console.log('Sample Rate:', sampleRate);
    };

    // Push audio chunks to buffer
    mediaRecorder.ondataavailable = handleDataAvailable;

    // Stop recording when mediaRecorder stops
    mediaRecorder.onstop = () => {
      console.log('Recording stopped');
    };
  } catch (error) {
    console.error('Error accessing microphone:', error);
  }
}

getSampleRate()