Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.1k views
in Technique[技术] by (71.8m points)

python - How would I stream audio from pytube to discord.py without downloading the mp3?

I've been attempting to find a way to create a play command for my discord bot. I want this play command to grab the youtube url and instead of downloading the songs, it plays the mp3 straight from the url. Are there any error that standout? One error I get is discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: search() missing 1 required positional argument: 'arg' My current code is:


import discord
import random
import asyncio
import youtube_dl
import os
import requests
from discord.ext import commands,tasks
from discord.utils import get
from discord import FFmpegPCMAudio
from discord.ext.commands import Bot, has_permissions, CheckFailure
from itertools import cycle
from youtube_dl import YoutubeDL
from requests import get
from os import system

def search(query, arg):
    with YoutubeDL({'format': 'bestaudio', 'noplaylist':'True'}) as ydl:
        try: requests.get(url)
        except: info = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]
        else: info = ydl.extract_info(arg, download=False)
    return (info, info['formats'][0]['url'])
async def join(ctx, voice):
    channel = ctx.author.voice.channel

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect() 
# Play
@client.command()
async def play(ctx, *, query):
    FFMPEG_OPTS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

    video, source = search(query)
    voice = get(client.voice_clients, guild=ctx.guild)

    await join(ctx, voice)
    await ctx.send(f'Now playing {info}.')
    voice.play(FFmpegPCMAudio(source, **FFMPEG_OPTS), after=lambda e: print('done', e))
    voice.is_playing()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...