如何将流包装成异步,使其在启动流之前等待名称解析



我目前正在做一个接收youtube网址的机器人,从技术上讲,它必须处理视频并将其转换为mp3。问题是流在分配 url 之前开始,因此返回错误

videoUrl = ""; //this is determined by the last bot.onText function, thats where its asigned
var saveLocation = "";
function saveName(){
return new Promise((resolve) => getInfo(videoUrl).then(info => {
saveLocation = "./"+info.items[0].title+".mp3";
resolve();
}))
}
stream = ytdl(videoUrl) //Problem is that this doesn't wait for that assignment to finish so videoUrl is empty, and I'm not sure how to implement an async there that awaits for the resolution

async function convert(){
const data = await saveName();
new ffmpeg({ source: stream, nolog: true }).toFormat('mp3').audioBitrate(320).on('end', function() {
console.log('file has been converted successfully');
})
.on('error', function(err) {
console.log('an error happened: ' + err.message);
})
.saveToFile(saveLocation); 
}


bot.onText(/^(http(s)??://)?(www.)?((youtube.com/watch?v=)|(youtu.be/))([a-zA-Z0-9-_])+/gm, (msg) => {
bot.sendMessage(msg.chat.id, msg.text)
videoUrl = msg.text; //this is where the asignmenet should happen
convert();
});

这是我对 await 应该如何为流工作的解释,但它不能正常工作

videoUrl = "";
var saveLocation = "";
function saveName(){
return new Promise((resolve) => getInfo(videoUrl).then(info => {
saveLocation = "./"+info.items[0].title+".mp3";
resolve();
}))
}
async function streaming(){  //made it async
const data = await saveName();
stream = ytdl(videoUrl)
}

async function convert(){
const data = await saveName();
streaming();  //it should be resolved by the time saveName is processed, so it shold start the stream, but it wont
new ffmpeg({ source: stream, nolog: true }).toFormat('mp3').audioBitrate(320).on('end', function() {
console.log('file has been converted successfully');
})
.on('error', function(err) {
console.log('an error happened: ' + err.message);
})
.saveToFile(saveLocation); 
}


bot.onText(/^(http(s)??://)?(www.)?((youtube.com/watch?v=)|(youtu.be/))([a-zA-Z0-9-_])+/gm, (msg) => {
bot.sendMessage(msg.chat.id, msg.text)
videoUrl = msg.text;
convert();
});

首先,在saveName中,您将退货承诺解析为未定义。应该是resolve(saveLocation);.

其次,如果您希望在设置videoUrl后创建stream,则只需将stream构造线移动到videoUrl分配线下方即可。

// change this:
stream = ytdl(videoUrl); // obviously videoUrl will be undefined.
...
bot.onText(..., (msg) => {
bot.sendMessage(msg.chat.id, msg.text)
videoUrl = msg.text; //this is where the asignmenet should happen
convert();
});
// into:
...
bot.onText(..., (msg) => {
bot.sendMessage(msg.chat.id, msg.text)
videoUrl = msg.text; //this is where the asignmenet should happen
stream = ytdl(videoUrl)
convert();
});

最新更新