2016-10-03 81 views
0

我使用的是Node.js(v4.4.7)的工作,並已經寫了幾行字來播放聲音...Node.js的暫停與恢復的setTimeout流()

const Speaker = require('audio-speaker/stream'); 
const Generator = require('audio-generator/stream'); 

const speaker = new Speaker({ 
     channels: 1,   // 1 channel 
     bitDepth: 16,   // 16-bit samples 
     sampleRate: 44100  // 44,100 Hz sample rate 
     }); 

// Streams sample values... 
const sound = new Generator(
     //Generator function, returns sample values 
     function (time) { 
       return Math.sin(Math.PI * 2 * time * 2000); 
     }, 
     { 
     //Duration of generated stream, in seconds, after which stream will end. 
     duration: Infinity, 

     //Periodicity of the time. 
     period: Infinity 
     }); 

// Pipe value stream to speaker 
sound.pipe(speaker); 

...歡呼,它的作品!現在,讓我們嘗試暫停聲音並在3秒後恢復它...

sound.pause(); 

setTimeout(()=>{ 
     sound.resume(); 
     console.log(sound.isPaused()); // => false 
}, 3000); 

...輝煌,那作品,以及!現在,讓我們嘗試相反並在3秒後暫停聲音...

setTimeout(()=>{ 
     sound.pause(); 
     console.log(sound.isPaused()); // => true/although sound is still playing 
}, 3000); 

...等等,爲什麼這不起作用?爲什麼sound.isPaused()顯示「true」,儘管聲音仍在播放。它是錯誤還是我做錯了什麼?

我瀏覽了Node.js文檔和一些關於Node.js中的流的教程,但無法找到解釋。在本教程中,他們只使用setTimout()來恢復流,但他們從來沒有說過爲什麼你不能以這種方式暫停一個流。

+0

分享無法使用的完整源代碼 – advncd

+0

這是什麼意思?這是完整的代碼。 – user2956577

+0

這是緩衝區嗎?您等待3秒鐘暫停,也許它在這段時間內緩衝數據,因此聲音繼續?它最終會停止嗎? –

回答

0

現在,我不知道爲什麼在可讀流上調用.pause()/。resume()沒有按預期工作。我最終在可寫入的流上調用了.cork()/。uncork(),達到了預期的效果。

setTimeout(()=>{ 
    speaker.cork(); 
}, 3000); 

setTimeout(()=>{ 
    speaker.uncork(); 
}, 3000); 

我會盡快更新此答案,對此行爲有解釋。