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

标签 javascript node.js settimeout node.js-stream

我正在使用 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);

...欢呼,它起作用了!现在,让我们尝试暂停声音并在 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() 来恢复流,但他们从未说明为什么你不能以这种方式暂停流。

最佳答案

目前,我不知道为什么在可读流上调用 .pause()/.resume() 没有按预期工作。我最终在可写流上调用了 .cork()/.uncork(),达到了预期的结果。

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

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

一旦我对这种行为有了解释,我就会更新这个答案。

关于javascript - Node.js 使用 setTimeout() 暂停和恢复流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39838057/

相关文章:

javascript - 棘手的 setTimeout 序列

javascript - 使用 setInterval() 刷新图像

javascript - JSON.parse UTF-8 字符串

javascript - 无法在 Angular js 中加载资源错误

node.js - Node.js中的exports.install是什么?

javascript - 套接字客户端返回变量

node.js - 从 Heroku 的子目录运行 npm

javascript 函数调用不工作

javascript - 使用 body-parser 和 express 解析嵌套的 JSON

使用 setTimeout 的 Javascript 重定向