目標
bin/music "謝安琪"
執行上面的命令,就能夠播放謝安琪的音樂,當播放完一首,可以接下去播放下一首。
參考
在寫這個項目的過程中,我也參考了阮一峰老師的es6教程,也參考了Binaryify的項目,在此先一并做出感謝。
babel
babel是js的“編譯器”,我們在使用es6的過程中,可以用babel把我們的項目編譯成es5的js文件。
npm install babel babel-preset-es2015 --save
首先我們在項目的根目錄下創建文件.babelrc
"presets": ["es2015"]
在package.json中的scripts下加入如下命令
"build": "babel src/ -d build/"
以后,我們只要運行npm run build就可以編譯src目錄下的文件,并將轉化后的es5的文件保存在build下
編寫api
先寫配置文件
// src/config.js
const origin = 'http://music.163.com'
const globalOption = {
headers: {
'Origin': origin,
'Referer': origin,
'Content-Type': 'application/x-www-form-urlencoded'
},
proxy:false
}
export { origin, globalOption }
然后實現搜索api,我們使用request庫來完成http請求,用promise而非callback實現了異步操作,
// src/search.js
import request from 'request'
import { origin, globalOption } from './config'
import { deepCopy } from './util'
const search = (name = null, limit = 3, offset = 0) => {
const option = deepCopy(globalOption)
const url = `${origin}/api/search/suggest/web`
const form = {
s: name,
limit,
type: 1,
offset
}
const method = 'POST'
Object.assign(option, { url, form, method })
return new Promise(function(resolve, reject){
request(option, (err, res, body) => {
if (!err && res.statusCode == 200) {
resolve(JSON.parse(body));
} else {
reject(err)
}
})
})
}
export { search }
同理,我們也可以實現getArtiestAlbums,getAlbums,song分別根據歌手id獲取歌手專輯,根據歌手專輯獲取歌手歌曲,根據歌曲id返回歌曲詳情。(代碼見github)
可執行文件 bin/music
#!/usr/local/bin/node
const api=require('../build/app.js').api
var exec = require('child_process').exec;
var name = process.argv[2]
調用api
#!/usr/local/bin/node
const api=require('../build/app.js').api
var exec = require('child_process').exec;
var name = process.argv[2]
api.search(name).then(function(data){
var artistid = data.result.artists[0].id
return api.getArtistAlbums(artistid)
}).then(function(albums){
var getsongsPromise = albums.map(function(album){
return api.getAlbums(album.id)
})
return Promise.all(getsongsPromise)
}).then(function(responses){
var res = []
for (var i = 0; i < responses.length; i++){
var tmp = responses[i].map(function(s){
return api.song(s.id)
})
res = res.concat(tmp)
}
return Promise.all(res)
}).then(function(songs){
var urls = songs.map(function(song){
return song.mp3Url
})
var names = songs.map(function(song){
return song.name
})
var i = 0
var play = (i) => {
console.log("正在播放:" ,name, " ",names[i])
exec("mplayer "+urls[i], {maxBuffer: 20 * 1024 * 1024}, (error, stdout, stderr) => {
play(++i)
})
}
play(i)
}).catch(function(err){
console.log(err)
})
這段代碼有幾個注意點,第一是在一個函數域中返回多個回調應該怎么做,第二是如何fork出一個子進程并在子進程結束時得到通知并fork出下一個子進程。第三是child_process的exec有maxBuffer,默認為200k,需要重設。
next
deepcopy怎么實現的,可以看我之前的文章。
隨機播放怎么實現?shufflle一下就好了,可以看我之前的文章。
發布
我們已經完成了代碼的編寫和測試,下面我們想發布到npmjs上。
先在package.json中加入bin
"bin": {
"netsound": "bin/music"
},
然后在根目錄下
npm publish
之后就可以通過,下面的命令來安裝和使用了
#安裝
npm install netsound -g
#聽U2的歌
netsound U2