异步写入PassThrough流

时间:2017-07-09 15:50:20

标签: node.js node.js-stream

我需要将wav文件读入内存,并将其重复传递给node-speaker。以下代码尝试执行此操作,但声音仅播放一次。为什么是这样?

const fs = require('fs')
const { PassThrough } = require('stream')
const { Reader } = require('wav')
const Speaker = require('speaker')

fs.readFile('sample.wav', (e, buffer) => {

  const speaker = new Speaker()
  const reader = new Reader()
  const pass = new PassThrough()

  reader.pipe(speaker)
  pass.pipe(reader)

  setInterval(() => {
    pass.write(buffer)
  }, 1000)

})

此外,如果两个播放事件快速连续发生,我想在新事件发生后立即切断原始事件。

更新

我已经取得了一些进展。以下代码现在重复播放示例,但每次写入speaker error: write() failed: 2556时样本都会缩短。

const fs = require('fs')
const { Reader } = require('wav')
const Speaker = require('speaker')

const chunks = []
const reader = new Reader()
const speaker = new Speaker()
const file = fs.createReadStream('sample.wav')

file.pipe(reader)
reader.on('data', c => chunks.push(c))

speaker.on('error', e => console.log(`speaker error: ${e.message}`))
reader.on('error', e => console.log(`reader error: ${e.message}`))

reader.on('end', () => {

  const buffer = Buffer.concat(chunks)

  setInterval(() => {
    console.log('writing')
    speaker.write(buffer)
  }, 1000)

})

0 个答案:

没有答案