gpt4 book ai didi

javascript - 如何将流包装为 async ,使其在启动流之前等待名称解析

转载 作者:行者123 更新时间:2023-12-02 23:08:47 27 4
gpt4 key购买 nike

我目前正在制作一个接收 youtube url 的机器人,从技术上讲它必须处理视频并将其转换为 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();
});

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

    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 中,您将返回 promise 解析为未定义。它应该是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();
});

关于javascript - 如何将流包装为 async ,使其在启动流之前等待名称解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57462266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com