我通過在本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
從我的角度來看
現在,因爲source
已經與var
關鍵字使它作用域定義,這是造成play()
功能,因此無法訪問pause()
。刪除var
關鍵字確實可以解決問題。有人可以向我保證我的推理是正確的嗎?這只是一個錯字,還是有一些我不理解的基本原理? (我已經檢查過這本書的勘誤表,並且在那裏沒有提及它。)
你是正確的。與其他全球變量一起聲明。 –
我不確定這兩個代碼示例是否真的被看作是單個實際應用程序的一部分。 – Pointy