scriptProcessorNode.onaudioprocess не может получить доступ к глобальным переменным
Я строю класс вокруг генератора 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? Любое понимание будет оценено!
2 ответа
Нет ошибки в 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){ ...
Я смог получить доступ 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);
}