Saturday 8 April 2017

node.js Error: write after end - AWS Polly

I am trying to use AWS Polly for speech synthesis in my node.js app. When I run the speak(text) function for the first time everything works fine however if I run it again I get this error:

events.js:160
  throw er; // Unhandled 'error' event
  ^

Error: write after end
at writeAfterEnd (/Users/noahchalifour/Desktop/HomeServer/Jarvis-Node/node_modules/readable-stream/lib/_stream_writable.js:229:12)
at Speaker.Writable.write (/Users/noahchalifour/Desktop/HomeServer/Jarvis-Node/node_modules/readable-stream/lib/_stream_writable.js:269:20)
at PassThrough.ondata (_stream_readable.js:555:20)
at emitOne (events.js:96:13)
at PassThrough.emit (events.js:188:7)
at PassThrough.Readable.read (_stream_readable.js:381:10)
at flow (_stream_readable.js:761:34)
at resume_ (_stream_readable.js:743:3)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)

Here is the code I am trying to run:

// AWS Polly
// Load the SDK
const AWS = require('aws-sdk')
const Stream = require('stream')
const Speaker = require('speaker')

// Create an Polly client
const Polly = new AWS.Polly({
    signatureVersion: 'v4',
    region: 'us-east-1'
})

// Create the Speaker instance
const Player = new Speaker({
  channels: 1,
  bitDepth: 16,
  sampleRate: 16000
})

function speak(text) {
    let params = {
        'Text': text,
        'OutputFormat': 'pcm',
        'VoiceId': 'Brian'
    }
    Polly.synthesizeSpeech(params, (err, data) => {
        if (err) {
            console.log(err.code)
            console.log('error');
        } else if (data) {
            if (data.AudioStream instanceof Buffer) {
                // Initiate the source
                var bufferStream = new Stream.PassThrough()
                // convert AudioStream into a readable stream
                bufferStream.end(data.AudioStream)
                // Pipe into Player
                bufferStream.pipe(Player)
            }
        }
    })
}

speak("Hello World!")

setTimeout(function() {
    speak("This is so cool!")  // error is here
}, 10000)



via Noah Chalifour

No comments:

Post a Comment