本文介绍了重新启动JavaScript中的振荡器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使振荡器在鼠标放在画布上时播放,而在没有鼠标时停止播放.但是,使用当前代码,页面加载后仅工作一次,当鼠标第二次出现在画布上时会发生错误:

I'm trying to make oscillator play when mouse is on canvas and stop when it's not. However, with current code, it works just once after loading page, when mouse is on canvas second time error occurs:

var ac = new window.AudioContext() || new window.webkitAudioContext();
var osc = ac.createOscillator();
var canvas1 = document.getElementById("canvas1");
canvas1.addEventListener("mouseover", playosc);
canvas1.addEventListener("mouseout", stoposc);

function playosc() {
    osc.frequency.value = 440;
    osc.connect(ac.destination);
    osc.start();
}

function stoposc() {
    osc.stop();
}

如何重新启动振荡器?谢谢.

How to restart oscillator? Thanks.

推荐答案

由于OscillatorNodes不可重用,因此每次都需要创建一个Oscillator对象.示例:

You would need to create an Oscillator object each time as the OscillatorNodes are not reusable. Example:

var canvas1 = document.getElementById("canvas1");
canvas1.addEventListener("mouseover", playosc);
canvas1.addEventListener("mouseout", stoposc);

var ac = new window.AudioContext() || new window.webkitAudioContext();
var osc;

function playosc() {
    osc = ac.createOscillator()
    osc.frequency.value = 440;
    osc.connect(ac.destination);
    osc.start();
}

function stoposc() {
    osc.stop();
}

请参阅此优秀博客文章指导.

这篇关于重新启动JavaScript中的振荡器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 21:10