我正在学习这本 O'Reilly 书中的一些网络音频教程:http://chimera.labs.oreilly.com/books/1234000001552/ch02.html#s02_2
以下代码应该创建一个系统来暂停音频文件并恢复播放。
// Assume context is a web audio context, buffer is a pre-loaded audio buffer.
var startOffset = 0;
var startTime = 0;
function pause() {
source.stop();
// Measure how much time passed since the last pause.
startOffset += context.currentTime - startTime;
}
function play() {
startTime = context.currentTime;
var source = context.createBufferSource();
// Connect graph
source.buffer = this.buffer;
source.loop = true;
source.connect(context.destination);
// Start playback, but make sure we stay in bound of the buffer.
source.start(0, startOffset % buffer.duration);
}
但是,运行 pause()
函数会导致以下错误:
Uncaught ReferenceError: source is not defined
现在从我的 Angular 来看,这是因为 source
已使用 var
关键字定义,使其作用域为 play()
函数,因此无法访问 pause()
。删除 var 关键字确实可以解决问题。有人可以让我放心我的推理是正确的吗?这只是一个错字,还是有一些我不理解的基本原理? (我检查了这本书的勘误表,那里没有提及它。)
最佳答案
将 source
设为全局变量,就像 startOffset
和 startTime
一样。
关于javascript - 函数内定义的变量导致引用错误 : not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364588/