gpt4 book ai didi

node.js - (Ffmpeg) 如何使用 Ffmpeg 从接收到的 UDP 数据包在浏览器中播放实时音频?

转载 作者:行者123 更新时间:2023-12-04 23:22:43 28 4
gpt4 key购买 nike

我有充当 UDP 服务器和 UDP 客户端的 .NET Core 控制台应用程序

  • UDP 客户端通过接收音频数据包。
  • UDP 服务器,通过发送每个接收到的数据包。

  • 这是控制台应用程序的示例代码:
    static UdpClient udpListener = new UdpClient();
    static IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.230"), 6980);
    static IAudioSender audioSender = new UdpAudioSender(new IPEndPoint(IPAddress.Parse("192.168.1.230"), 65535));

    static void Main(string[] args)
    {
    udpListener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    udpListener.Client.Bind(endPoint);

    try
    {
    udpListener.BeginReceive(new AsyncCallback(recv), null);
    }
    catch (Exception e)
    {
    throw e;
    }

    Console.WriteLine("Press enter to dispose the running service");
    Console.ReadLine();
    }

    private async static void recv(IAsyncResult res)
    {
    byte[] received = udpListener.EndReceive(res, ref endPoint);
    OnAudioCaptured(received);
    udpListener.BeginReceive(new AsyncCallback(recv), null);
    }

    另一方面,我有一个 Node js API 应用程序,它假设将 FFmpeg 命令作为子进程执行并执行以下操作
  • 从控制台应用程序 UDP 服务器接收音频数据包作为输入。
  • 将接收到的字节转换为 WebM
  • 将结果输出到响应中。

  • 最后,在客户端,我应该有一个源值等于 http://localhost:3000 的音频元素。

    目前,我只能执行这个 FFmpeg 命令:
    ffmpeg -f  s16le  -ar 48000 -ac 2 -i 'udp://192.168.1.230:65535' output.wav

    执行以下操作
  • 接收 UDP 数据包作为输入
  • 将接收到的字节转换为 output.wav 音频文件。

  • 我将如何在接收 UDP 数据包的 Node js 服务器中执行子进程并将结果作为 Webm 输出到响应中?

    最佳答案

    非常感谢布拉德,他指导我找到解决方案。

    在 Node js 服务器中,我必须执行以下操作

  • 将 Ffmpe 作为子进程执行,接收 UDP 数据包作为输入
  • 将子进程的每个结果通过管道输出到响应中。

  • 这是node js服务器的源代码:
    var http = require("http");
    var port = 8888;
    var host = "localhost";
    var children = require("child_process");

    http
    .createServer(function (req, res) {
    //ffmpeg -f s16le -ar 48000 -ac 2 -i 'udp://192.168.1.230:65535' -b:a 128k -f webm -
    var ffm = children.spawn(
    "ffmpeg",
    "-f s16le -ar 48000 -ac 2 -i udp://192.168.1.230:65535 -b:a 128k -f webm -".split(
    " "
    )
    );

    res.writeHead(200, { "Content-Type": "audio/webm;codecs=vorbis" });
    ffm.stdout.on("data", (data) => {
    console.log(data);
    res.write(data);
    });
    })
    .listen(port, host);

    console.log("Server running at http://" + host + ":" + port + "/");

    客户端:
      <audio src="http://loclahost:8888" type='audio/webm; codecs="vorbis"' controls preload="none"></audio>

    关于node.js - (Ffmpeg) 如何使用 Ffmpeg 从接收到的 UDP 数据包在浏览器中播放实时音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62006071/

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