1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Discord.net/Discord.py record audio stream of user or whole channel

Discussão em 'Python' iniciado por Stack, Setembro 27, 2024 às 23:12.

  1. Stack

    Stack Membro Participativo

    I am currently trying to record audio of a specific user or if not possible of the whole channel.

    I started with Discord.py but was not successful. Currently the bot joins a channel when a specific user connects and should start recording. With python and C# I found old posts and github threads which supplied solutions to my problem but this solutions does not seem to work anymore. Did discord remove support for fetching the audio streams?

    I would love to havet his feature but I do not find that much information. Playing audio is currently atleast in python no problem.

    Coding:

    private Task OnVoiceStateUpdated(SocketUser? socketUser, SocketVoiceState before, SocketVoiceState after)
    {
    _ = Task.Run(async () =>
    {
    try
    {
    Logger.Output($"Starting to handle user movements", Logger.LogType.Default);
    var currentChannel = after.VoiceChannel ?? before.VoiceChannel;
    if (currentChannel == null) return;
    var botUser = currentChannel.Guild.Users.FirstOrDefault(u => u.IsBot);

    if (before.VoiceChannel == null && after.VoiceChannel != null) // If member joins a voice channel
    {
    var channel = after.VoiceChannel;

    try
    {
    Logger.Output($"Connect bot to channel '{channel.Name}'", Logger.LogType.Default);
    await Task.Delay(1000);
    _audioClient = await channel.ConnectAsync();
    _cts = new CancellationTokenSource();


    if (socketUser is not SocketGuildUser socketGuildUser) return;
    if (socketGuildUser.AudioStream is not InputStream inputStream) return;

    _ = Task.Run(() =>
    ProcessAudioAsync(inputStream)
    );
    }
    catch (Exception e)
    {
    Logger.Output($"Failed to connect and start recording: {e}", Logger.LogType.Error);
    }
    }
    }
    catch (Exception e)
    {
    Logger.Output($"Handling user movements failed! {e.Message}", Logger.LogType.Error);
    }
    });
    return Task.CompletedTask;
    }

    private async Task ProcessAudioAsync(InputStream inputStream)
    {
    // Create a new wave file writer to save the audio stream
    string currentTime = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
    string filename = Path.Combine(AudioRecordingsPath, $"output_{currentTime}.wav");

    // Create the wave file writer to save the audio stream
    _writer = new WaveFileWriter(filename, new WaveFormat(48000, 16, 2));

    try
    {
    var buffer = new byte[81920]; // Buffer size can be adjusted as needed

    while (!_cts.IsCancellationRequested)
    {
    var bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length, _cts.Token);

    // If bytesRead is zero, end of the stream has been reached
    if (bytesRead == 0)
    {
    Task.Delay(1000).Wait();
    continue;
    }

    // Write from buffer to wave file
    await _writer.WriteAsync(buffer, 0, bytesRead);

    // Flush the writer to ensure data is written to disk
    await _writer.FlushAsync();
    }
    }
    catch (OperationCanceledException e)
    {
    Logger.Output($"Audio processing was cancelled. {e.Message} {e.StackTrace}", Logger.LogType.Error);
    }
    catch (TimeoutException e)
    {
    Logger.Output($"Audio processing timed out. {e.Message} {e.StackTrace}", Logger.LogType.Error);
    }
    catch (InvalidOperationException e)
    {
    Logger.Output($"Audio processing failed due to stream issue. {e.Message} {e.StackTrace}",
    Logger.LogType.Error);
    }
    catch (Exception e)
    {
    Logger.Output($"Audio processing failed. {e.Message} {e.StackTrace}", Logger.LogType.Error);
    }
    finally
    {
    await inputStream.FlushAsync();
    }
    }


    The problem seems to be in this line "var bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length, _cts.Token);" the function is called but never returns. It seems the stream never contains any data.

    Is there a possible solution for this in C# or Python?

    Thank you very much!

    Continue reading...

Compartilhe esta Página