PK Creative Spring Festival, I am participating in the “Spring Festival Creative Submission Contest”, please see: Spring Festival Creative Submission Contest”

The main idea is to convert the text to MP3, and then let the system, automatically play the MP3 file. That’s basically what we’re looking for.

Text to MP3 audio, with the help of Baidu API

1. Invoke baidu API to generate token

First, you need to log in to the official website of Baidu Cloud to create an application

Enter the corresponding parameters according to the procedure on the official website and use Postman to generate the token.

After the token is generated, query-String is used to format the parameters and http.request is used to send the request.

let http = require('http');
let querystring = require('query-string');
let fs = require('fs');
let path = require('path');
​
let text = "The stars all over the sky shine with auspicious light; Warm lights, send out the halo of happiness; Colorful fireworks, bloom beautiful colors; The bell of peace, open a new era; Cooked dumplings, sending out qin nose aroma; Sincere blessing, transfer infinite truth: I wish you a happy New Year's Eve, free and unfettered joy! ,"let postData = querystring.stringify({
  "lan": "zh"."ctp": 1."cuid": "abcd"."tok": "24. Ca350a1d49bc336f0fa9814e2ed0a2f8. 2592000.1644076738.282335-25475942"."ie": "UTF-8"."tex": text,
  "vol": 9."per": 0."spd": 5."pit": 5."aue": 3
});
​
let options = {
  "method": "GET"."hostname": "tsn.baidu.com"."path": "/text2audio?" + postData
};
Copy the code

Build the parameters we need.

Send requests using http.request.

After the request is returned, it is concatenated using buffer.concat.

let req = http.request(options, function (res) {
  var chunks = [];
  res.on("data".function (chunk) {
    chunks.push(chunk);
  });
​
  res.on("end".function () {
    var body = Buffer.concat(chunks);
    var filePath = path.normalize('./iloveu.mp3');
    fs.writeFileSync(filePath, body);
  });
});
​
req.end();
Copy the code

Generate MP3 files.

By this point, our first small goal has been accomplished.

Next, we use play-sound to play the audio.

Play-sound: Play sounds by Shelling out to one of the available audio players.

Examples from the official website

var player = require('play-sound')(opts = {})

// $ mplayer foo.mp3 
player.play('foo.mp3'.function(err){
  if (err) throw err
})

// { timeout: 300 } will be passed to child process
player.play('foo.mp3', { timeout: 300 }, function(err){
  if (err) throw err
})

// configure arguments for executable if any
player.play('foo.mp3', { afplay: ['-v'.1 ] /* lower volume for afplay on OSX */ }, function(err){
  if (err) throw err
})

// access the node child_process in case you need to kill it on demand
var audio = player.play('foo.mp3'.function(err){
  if(err && ! err.killed)throw err
})
audio.kill()
Copy the code

Use play-sound to play the generated MP3

const path = require('path');
var player = require('play-sound')(opts = {})
​
player.play(`${path.resolve(__dirname, 'iloveu.mp3')}`.function(err){
  if (err) throw err
})
Copy the code

Package.json

{
  "name": "node_audio"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo "Error: no test specified" && exit 1"."start": "node main.js && node demo.js"
  },
  "keywords": []."author": ""."license": "ISC"."dependencies": {
    "http": "^ 0.0.1 ws-security"."iconv-lite": "^ 0.6.3"."play-sound": "^ 1.1.4." "."query-string": "^ 7.1.0"."querystring": "^ 0.2.1"}}Copy the code

Run NPM run Start to play New Year’s greetings.

PS: I don’t know how to call the voice on the MAC. Windows users can call Windows voice.

npm install iconv-lite
Copy the code
const { exec } = require('child_process');
const iconv = require('iconv-lite');

exec(`powershell.exe Add-Type -AssemblyName System.speech; $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; $speak.Rate = 3; $speak.Speak([Console]::In.ReadLine()); exit`)
.stdin.end(iconv.encode('There is no such thing as an amicable breakup, preceded by "quarrels, cold wars, indifference, strangeness." Peace is just a facade, Voltaire said. In an avalanche, no snowflake wants to admit that he is the cause of the avalanche. Like the slow ebb of the sea, like the moon over a hill, like the gradual diminution of a symptom, it is all the same. '.'gbk'));
Copy the code

If you are interested, you can try it.