我有点难以使用 Tone.js 从缓冲区对象创建声音
应该很简单,但我在陌生的领域。来自 chatGPT 的越来越无用的建议让我很困惑。
这是代码(我知道代码有点乱。抱歉,我什至无法简化它)
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;
我只想填充
buffer(bufferArray[chunkSize])
并覆盖bufferArray
并连续播放它。