首页 > 解决方案 > 在 ts/js 和电子中使用 setInterval 播放音频

问题描述

我正在用电子创建一个节拍器,使用嚎叫器播放音频。

当窗口在屏幕上时,音频会按应有的方式播放,但是当我最小化窗口时,音频开始以错误的间隔播放并且节拍器出现故障。

这些是我用来播放节拍的音频

const mainBeat = new Howl({
  src: ["sounds/Boutique808.mp3"],
  onplayerror: (e) => console.log(e),
});
const secondBeat = new Howl({
  src: ["sounds/tick.mp3"],
  onplayerror: (e) => console.log(e),
});

startBeats 函数创建由函数 bpmToMs 计算的间隔,如果 bpm 为 60,则结果为 750ms

如果 currentBeat 为 1 或 0 则函数 playBeat 播放 mainBeat 否则播放第二个节拍

startBeats = (..._: any[]) => {
   this.setState({ playing: true });
   this.playBeat();
   this.beatInterval = setInterval(() => {
     this.playBeat();
   }, bpmToMs(this.state.currentBpm));
};

playBeat = () => {
   this.incrementBeat();
   if (this.state.currentBeat === 1 || this.state.currentBeat === 0)
     mainBeat.play();
   else secondBeat.play();
};

我已经从我的 react 类组件中复制了必要的行,所以不用担心意外的单独语法:)

标签: javascriptreactjstypescriptelectronhowler.js

解决方案


我通过在电子 webPreferences 中添加backgroundThrottling: false解决了这个问题

mainWindow = new MainWindow({
    width: width,
    height: height,
    minWidth: width,
    minHeight: height - 300,
    maxWidth: width,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      backgroundThrottling: false,
    },
    icon: path.join(__dirname, "assets/icons/png/1204x1024.png"),
  });

现在它工作得很好!


推荐阅读