我正在围绕scriptProcessorNode振荡器构建类。我已将onaudioprocess
事件处理程序包装在函数Gendy.prototype.process
中。我可以从这个包装器函数中访问全局变量和函数,但是不能从onaudioprocess
函数中访问它们。
我设计了一个解决属性的方法,在包装函数中重新定义它们,但是当尝试使用this.walk()
调用另一个方法,随机游走方法时,这不起作用。
这是我的代码:
Gendy.prototype.process = function(){
var point = 0;
var index = 0;
var y = 0;
var breakpoint = this.breakpoint;
var freq = this.freq;
var walk = this.walk();
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
var outputBuffer = audioProcessingEvent.outputBuffer;
var outputData = outputBuffer.getChannelData(0);
for(var j = 0; j < outputData.length;j++){
// linearly interpolate between the new breakpoint positions
// get the interp point by comparing index to the x distance
var lerp = (index - breakpoint[point].x) / (breakpoint[point+1].x - breakpoint[point].x);
y = lerp * (breakpoint[point+1].y - breakpoint[point].y) + breakpoint[point].y;
if(point < breakpoint.length && index >= breakpoint[point+1].x) {
point++;
}
outputData[j] = y;
index+=freq;
if(index >= breakpoint[breakpoint.length-1].x){
index = 0;
point = 0;
walk();
}
}
}
}
这会产生声音,但会返回错误:
Uncaught TypeError: walk is not a function
几行,然后
Uncaught TypeError: undefined is not a function
永远。
这是scriptProcessorNode的错误吗?任何见解都将不胜感激!
答案 0 :(得分:1)
scriptProcessorNode中没有错误,问题是以下行:
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
this
内的onaudioprocess
变量默认情况下会引用this.scriptNode
对象,您可以通过以下两种方式之一处理它:
使用bind
(正如您在答案中所做的那样):
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
...
}.bind(this)
使用局部变量来保存this
的值,并使用该局部变量代替this
:
var self = this;
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
...
答案 1 :(得分:0)
通过将this
附加到onaudioprocess
功能,我可以从.bind(this)
功能中访问Gendy.prototype.process = function(){
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
var outputBuffer = audioProcessingEvent.outputBuffer;
var outputData = outputBuffer.getChannelData(0);
for(var j = 0; j < outputData.length;j++){
// linearly interpolate between the new breakpoint positions
// get the interp point by comparing index to the x distance
var lerp = (this.index - this.breakpoint[this.point].x) / (this.breakpoint[this.point+1].x - this.breakpoint[this.point].x);
this.y = lerp * (this.breakpoint[this.point+1].y - this.breakpoint[this.point].y) + this.breakpoint[this.point].y;
if(this.point < this.breakpoint.length && this.index >= this.breakpoint[this.point+1].x) {
this.point++;
}
outputData[j] = this.y;
this.index+=this.freq;
if(this.index >= this.breakpoint[this.breakpoint.length-1].x){
this.index = 0;
this.point = 0;
this.walk();
}
}
}.bind(this);
}
。
以下是代码:
None