Node 实现播放新年祝福语

896 阅读2分钟

PK创意闹新春,我正在参加「春节创意投稿大赛」,详情请看:春节创意投稿大赛

图片.png

主要的思路就是将文字转为 MP3,再让系统,自动播放该 MP3 文件。大致就可以实现我们想要的效果了。

文字转为 mp3 音频,借助百度 API

1. 调用百度 API,生成 token

首先需要登录百度云的官网,创建应用

图片.png

根据官网使用步骤,传入对应的参数,使用 postman 生成 token。

生成 token 之后,使用 query-string 来格式化参数,使用 http.request 来发送请求。

let http = require('http');
let querystring = require('query-string');
let fs = require('fs');
let path = require('path');
​
let text = "满天的星斗,闪耀吉祥的光芒;温馨的灯火,散发幸福的光晕;缤纷的礼花,绽放美好的色彩;平安的钟声,开启崭新的纪元;煮好的饺子,散发沁鼻的香气;真挚的祝福,则传递无限的真情:祝你除夕夜开心,自在逍遥乐翻天!,"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
};

将我们需要的参数构建完成。

使用 http.request 发送请求。

请求返回之后,使用 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();

生成 mp3 文件。

截止到这一步,我们的第一个小目标就完成了。

接下来,我们借助 play-sound,来完成播放音频。

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

官网给出的例子

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()

使用 play-sound 播放生成的 mp3

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

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-security",
    "iconv-lite": "^0.6.3",
    "play-sound": "^1.1.4",
    "query-string": "^7.1.0",
    "querystring": "^0.2.1"
  }
}

图片.png

运行 npm run start 开始播放新年祝福吧。

PS:目前不知道怎么调用 MAC 电脑上的语音。用 windows 系统的小伙伴,可以调用 windows 的语音。

npm install iconv-lite
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('其实根本没有什么和平分手,在那之前总会经历“争吵、冷战、无视、陌生”所谓的和平只是表象,伏尔泰说,在雪崩的时候,没有一片雪花想要承认,自己是雪崩的罪魁祸首。就像海水慢慢退潮,像月亮落下山头,像一种症状的逐渐消退,都是一样的', 'gbk'));

感兴趣的小伙伴可以试一下。