2013-10-14 86 views
0

我通過在本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關鍵字確實可以解決問題。有人可以向我保證我的推理是正確的嗎?這只是一個錯字,還是有一些我不理解的基本原理? (我已經檢查過這本書的勘誤表,並且在那裏沒有提及它。)

+0

你是正確的。與其他全球變量一起聲明。 –

+0

我不確定這兩個代碼示例是否真的被看作是單個實際應用程序的一部分。 – Pointy

回答

0

在函數中聲明變量使其成爲局部變量,即它只存在於該函數中,因此只能在該函數中引用。聲明它作爲一個全局變量將其提供給任何JavaScript函數,但一般要污染儘可能少的全局命名空間:

function AudioPlayer(buffer) { 
    this.startOffset = 0; 
    this.startTime = 0;  
    this.source = null; 
    this.buffer = buffer; 
} 

AudioPlayer.prototype.pause = function() { 
    if (!this.source) { 
    return; 
    } 
    this.source.stop(); 
    // Measure how much time passed since the last pause. 
    this.startOffset += context.currentTime - this.startTime; 
} 

AudioPlayer.prototype.play = function() { 
    this.startTime = context.currentTime; 
    this.source = context.createBufferSource(); 
    // Connect graph 
    this.source.buffer = this.buffer; 
    this.source.loop = true; 
    this.source.connect(context.destination); 
    // Start playback, but make sure we stay in bound of the buffer. 
    this.source.start(0, this.startOffset % this.buffer.duration); 
} 

,它允許你調用這些函數,像這樣:

var player = new AudioPlayer(buffer); 
player.play(); 
player.pause(); 
2

使source成爲一個全局變量,就像startOffsetstartTime一樣。

+0

另外,您可能需要一個「0」作爲停止參數(0),至少在Webkit上。 – cwilso

0

試試這個:

function a(advName,area) { 
    onclick="sub(\'' +advName+ '\',\'' +area+ '\');" 
} 
+0

如果你給出了答案的直覺以及代碼,那會更好。 – vefthym