javascript - tone.js:如何知道 triggerRelease 何时完成

标签 javascript tone.js

我想在音符播放完毕后使用 tone.js 更新我的 UI

const now = Tone.now()
synth.triggerAttack("G3", now);
synth.triggerRelease("G3", now + 60 / this.tempo)

如何获取回调或向 triggerRelease 添加监听器以便更新 UI?

最佳答案

我从未使用过该库,但查看其文档后发现该 API 似乎定义了一个 onsilence您可以用于您的目的的回调。

您可以在 creating the Synth instance 时提供该回调传递适当的 configuration option :

const synth = new Tone.Synth({
  onsilence: () => console.log('I am invoked after the release has finished') // update the UI as appropriate
}).toDestination();
const now = Tone.now()
synth.triggerAttack("G3", now);
synth.triggerRelease(now + 60 / this.tempo);

API 提供了一些 tests也与之相关。

正如您在评论中指出的那样,onsilence 回调似乎仅在乐器完全静音时才会被调用,但您需要在音符结束时执行一些操作。

可能要走的路是使用不同的 events由图书馆提供。

库文档提供了different related examples举例说明如何使用它们。

考虑实例审查this one和同伴wiki page尝试解释如何同步视觉效果,或者这个 other one , 接近您正在寻找的每个音符回调。

这两个示例可以在 tone.js repository 中找到.

考虑到这些,考虑例如 this code ,基于描述 Part event 时提供的第二个示例以及 aforementioned article 中提供的代码片段关于性能以及如何同步视觉效果:

import * as Tone from 'tone';

const synth = new Tone.Synth().toDestination();
// use an array of objects as long as the object has a "time" attribute
const part = new Tone.Part(
  (time, value) => {
    // the value is an object which contains both the note and the velocity
    synth.triggerAttackRelease(value.note, '8n', time);

    Tone.Draw.schedule(function () {
      //this callback is invoked from a requestAnimationFrame
      //and will be invoked close to AudioContext time
      document.getElementById('app').innerHTML += ' ' + value.note;
    }, time);
  },
  [
    { time: 0, note: 'C3' },
    { time: '0:2', note: 'C4' },
  ]
).start(0);
Tone.Transport.start();

请重新加载 Stackblitz 中的预览页面,您应该会看到每条注释。

最后,如果您需要访问父上下文 this 对象,您有多种方法,如您的评论中所示:具体方法取决于您的实际代码。请考虑例如审查此相关 SO question ,我认为这可能会有所帮助。

关于javascript - tone.js:如何知道 triggerRelease 何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72178098/

相关文章:

javascript - 如何在javascript中合并多个对象?

javascript - 将类与函数绑定(bind)

javascript - 暂停 youtube 视频,youtube api

javascript - 如何更改 infobubble 上的 anchor

Javascript替换几个字符,包括 '/'

javascript - 无法切换 ToneJS 振荡器的 start()/stop()

javascript - Tone.js - AudioContext 不允许启动

javascript - 节拍器播放时数音符