【发布时间】:2022-02-08 22:24:45
【问题描述】:
我正在尝试使用元素中的 currentTime 属性的值来更新状态变量。我在 'timeupdate' 事件中添加了一个事件侦听器,因此我可以使用 currentTime 的值调用 setPosition(位置用于将旋钮定位在代表歌曲播放的滑块上)。
但是,检索 audioElement.currentTime 并将结果用作 setPosition 的参数会使我的浏览器(Chrome 和 Safari)崩溃。事实上,我的 MacBook 上的活动监视器显示本地网站使用的线程数随着音频文件的播放而不断增加,但我不确定这意味着什么。该站点也使用大量内存,但仅在为每个“timeupdate”事件检索 currentTime 属性时。
我不知道是什么导致我的组件出现性能问题,至少我认为这是一个性能问题。
播放的音频文件是.wav
function SongPlayer({ file }) {
const [audioElement] = useState(new Audio(file));
const [playing, setPlay] = useState(null);
const [audioContext] = useState(new AudioContext({ sampleRate: 44100 }));
const [gainNode] = useState(audioContext.createGain());
const [position, setPosition] = useState(0);
useEffect(
() => {
const track = audioContext.createMediaElementSource(audioElement);
track.connect(gainNode).connect(audioContext.destination);
audioElement.addEventListener('timeupdate', () => {
setPosition(audioElement.currentTime);
});
},
[],
);
useEffect(
() => {
if (playing) audioElement.play();
else if (!playing) audioElement.pause();
},
[playing],
);
return (
<>
</>
);
}
export default SongPlayer;
localhost using +500 threads and over 1Gb of memory
编辑:
问题是当我调用new AudioContext() 作为初始状态值时。
每次渲染都会调用构造函数。
这篇文章帮助我弄清楚并很好地解释了它:https://stackoverflow.com/a/64131447/13757284
【问题讨论】:
-
很好地解释了修复!!:stackoverflow.com/a/64131447/13757284
标签: javascript html reactjs web web-audio-api