Skip to content

Instantly share code, notes, and snippets.

@ArnabXD
Last active August 19, 2021 15:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArnabXD/fdcdfa27d71c69236c1cccd2dd6eccf4 to your computer and use it in GitHub Desktop.
Save ArnabXD/fdcdfa27d71c69236c1cccd2dd6eccf4 to your computer and use it in GitHub Desktop.
import ytdl from 'ytdl-core';

// ....
 
fastify.get('/ytmp3', async (req, res) => {
        let { id, lang } = req.query;
        if (!ytdl.validateID(id)) {
            res.send({
                result: false,
                error: "Invalid ID"
            })
        }
        try {
            let ytdata = await ytdl.getInfo(`https://youtube.com/watch?v=${id}`, { lang: lang ?? 'en' })
            let audio = ytdata.player_response.streamingData.adaptiveFormats.filter((d) => d.mimeType.startsWith("audio"))
            res.send({
                result: true,
                audio
            })
        } catch (err) {
            res.send({
                result: false,
                error: String(err)
            })
        }
    })
@roj1512
Copy link

roj1512 commented Aug 19, 2021

Some notes:

  • lang ?? 'en' can lead to the language being empty, you can use || instead.
  • You can use ytdl.validateURL to accept both URLs and IDs.
  • You can remove the fastify.get and res.send parts to make it usable for any http library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment