我在 Javascript 中定义了一个类,用作与 iOS 兼容的音频播放器。我刚刚开始了解基础知识,并在尝试访问类方法时遇到问题。
创建类 ( var audio = new WebAudio('soundfile.mp3', document.querySelector(#sound_div))的实例并尝试访问该方法后audio.playSound(),我得到:
ReferenceError: Can't find variable: elem on line 29
class WebAudio {
constructor(soundFile, elem) {
this.soundFile = soundFile;
this.elem = elem;
}
context() {
var AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
return context;
}
webAudioTouchUnlock(context) {
return new Promise(function (resolve, reject) {
//if AudioContext is suspended, and window has been interacted with
if (context.state === 'suspended' && 'ontouchstart' in window) {
console.log(context.state);
var unlock = function() {
//resume AudioContext (allow playing sound), remove event listeners
context.resume().then(function() {
console.log("context resumed");
this.elem.removeEventListener('touchstart', unlock);
this.elem.removeEventListener('touchend', unlock);
resolve(true);
}, function (reason) {
reject(reason);
});
};
this.elem.addEventListener('touchstart', unlock, false); //error
this.elem.addEventListener('touchend', unlock, false);
} else {
console.log('context not suspended? Context is ' + context.state);
resolve(false);
}
});
}
playSound() {
this.webAudioTouchUnlock(this.context()).then(function (unlocked) {
if(unlocked) {
console.log('playing audio file');
var audio = new Audio('sound/' + soundFile);
if (!audio.playing) {
audio.play();
} else {
audio.pause();
}
}
}
慕森王
相关分类