简体   繁体   English

Node.js使用setTimeout()暂停和恢复流

[英]Node.js pausing and resuming streams with setTimeout()

I'm working with Node.js (v4.4.7) and have written a few lines to play a sound ... 我正在使用Node.js(v4.4.7),并写了几行代码来播放声音...

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);

...hurray, it works! ……万事大吉! Now, let's try to pause the sound and resume it after 3 seconds ... 现在,让我们尝试暂停声音并在3秒后恢复声音...

sound.pause();

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

... brilliant, that works as well! ...太棒了,效果也不错! And now, let's try the opposite and pause the sound after 3 seconds ... 现在,让我们尝试相反的做法,并在3秒后暂停声音...

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

... wait, why is this not working? ...等等,这为什么不起作用? And why does sound.isPaused() shows "true" although sound is still playing. 为什么sound.isPaused()会显示“ true”,尽管声音仍在播放。 Is it bug or am I doing something wrong? 是bug还是我做错了什么?

I went through the Node.js documentation and a couple of tutorials about streams in Node.js and could not find an explanation.In this tutorials they only use setTimout() to resume streams, but they never say anything about why you can not pause a stream this way. 我浏览了Node.js文档和一些关于Node.js中流的教程,但找不到说明。在这些教程中,他们仅使用setTimout()恢复流,但他们从不说什么为什么不能暂停这样的流。

For now, I don't know why calling .pause()/.resume() on the readable stream is not working as expected. 目前,我不知道为什么在可读流上调用.pause()/。resume()不能按预期方式工作。 I ended up calling .cork()/.uncork() on the writable stream, that achieves the desired result. 我最终在可写流上调用了.cork()/。uncork(),从而达到了预期的效果。

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

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

I will update this answer as soon I have an explanation for this behaviour. 一旦对此行为做出解释,我将更新此答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM