I am a bit struggling to create a sound from a buffer object with Tone.js
It should be simple, but I am in unfamiliar territory. And increasingly unuseful suggestions from chatGPT discombobulated me very.
Here is the code (I know the code is a bit messy. Sorry for that, I couldn’t make it even simplified)
import React, { useEffect, useState } from 'react';
import * as Tone from 'tone';
function AudioPlayer() {
const [isPlaying, setIsPlaying] = useState(false);
const chunkSize = 1024;
const bufferArray = new Float32Array(chunkSize);
const sampleRate = 16384;
let t = 0;
let x = 0;
const context = Tone.context;
const buffer = context.createBuffer(1, chunkSize, sampleRate);
// const source = context.createBufferSource(); <= do I really need this!
const player = new Tone.Player(buffer).toDestination();
useEffect(() => {
while (isPlaying){
for (let i = 0; i < chunkSize; i++) {
bufferArray[i] = Math.sin(2 * Math.PI * 440 * x);
t++;
x = t / sampleRate;
}
// buffer.fromArray(bufferArray); <= is there a simple method that just override on buffer?
}
}, [isPlaying]);
const handlePlayClick = async () => {
setIsPlaying(true);
player.start()
};
const handleStopClick = () => {
setIsPlaying(false);
player.stop()
};
return (
<div>
{!isPlaying && (
<button onClick={handlePlayClick}>Play</button>
)}
{isPlaying && (
<button onClick={handleStopClick}>Stop</button>
)}
</div>
);
}
export default AudioPlayer;
I just want to fill the buffer(bufferArray[chunkSize])
and override the bufferArray
and play it continuously.
2
Answers
Here is an answer -not quite, but works- for the question that I asked.
I have close to zero idea what I’m doing and I’m not sure I understand the question, but I played around a bit; does the following help at all?:
Things I looked at: