PowerShell

Play with Speech Synthesizer using PowerShell and Node JS

This blog post is to demo the speech synthesizer using PowerShell. What’s new? Well nothing, except blending the PowerShell script with Node JS. To know about Speech Synthesizer refer MSDN – Reference for PowerShell is captured in idera PowerShell Tip (Speech-Week) Yes, this reminded a project I delivered for one of our Dutch customer!

Now, it’s time to click and convert text to speech! Let’s make it as simple as possible! The speech page is illustrated below!

PowerShell Script

param (
    $Text 
)

process {
    Add-Type -AssemblyName System.Speech
    $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
    $speak.Speak($Text)
}

Pretty straight forward! The script accepts a parameter $Text and we pass value from our node web application.

Server.JS

var express = require('express'),
    bodyparser = require('body-parser'),
    app = express(),
    shell = require('node-powershell'),
    ps = new shell({
        executionPolicy: 'bypass',
        noProfile: true
    }),
    path = require('path');

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug');
app.use(bodyparser.urlencoded({
    extended: false
}));
app.use(bodyparser.json())
app.get('/', function (request, response) {
    response.render('index', {
        title: "Node PowerShell"
    })
});
app.get('/Speech', function (request, response) {
    response.render('speech', {
        title: "Speech To Text"
    })
})
app.post('/Speech', function (request, response) {
    ps.addCommand("./scripts/SpeakDemo.ps1", [ {
        name: 'Text',
        value: request.body.Text
    } ])
    ps.invoke().then(output => {
        console.log(output)
    })
})
app.listen(3000)
console.log("Your application is running on http://localhost:3000")

We have created two routes i.e GET and POST for ‘/Speech’ where the GET renders the speech.pug and POST calls the PowerShell script. Closer look to pass the value for the PowerShell parameter

ps.addCommand("./scripts/SpeakDemo.ps1", [ {
        name: 'Text',
        value: request.body.Text
} ])

speech.pug

block content
    h1 #{title}
    form(action="/Speech", method="post")
        #form-group
            label Your Text:
            input.form-control(name="Text", type="text")
            br
            br
            input.btn.btn-primary(type="submit" , value="Speak")

Use your favorite bootstrap to make your web application glossy! See you all in my next blog post! Enjoy PowerShell!

Leave a Reply

Your email address will not be published. Required fields are marked *