注意
点击这里下载完整示例代码
StreamWriter 高级用法¶
作者:Moto Hira
本教程展示如何使用torchaudio.io.StreamWriter
播放音频和视频。
警告
从 2.8 版本开始,我们正在重构 TorchAudio,以使其进入维护阶段。因此:
本教程中描述的 API 在 2.8 版本中已被弃用,并将在 2.9 版本中移除。
PyTorch 用于音频和视频的解码和编码功能正在被整合到 TorchCodec 中。
请参阅 https://github.com/pytorch/audio/issues/3902 获取更多信息。
注意
本教程使用硬件设备,因此它不可跨不同的操作系统移植。
本教程是在 MacBook Pro(M1,2020)上编写和测试的。
注意
本教程需要 FFmpeg 库。详情请参阅 FFmpeg 依赖项。
警告
TorchAudio 动态加载系统上安装的兼容 FFmpeg 库。支持的格式类型(媒体格式、编码器、编码器选项等)取决于这些库。
要检查可用设备、多路复用器和编码器,可以使用以下命令
ffmpeg -muxers
ffmpeg -encoders
ffmpeg -devices
ffmpeg -protocols
准备¶
import torch
import torchaudio
print(torch.__version__)
print(torchaudio.__version__)
from torchaudio.io import StreamWriter
from torchaudio.utils import download_asset
AUDIO_PATH = download_asset("tutorial-assets/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav")
VIDEO_PATH = download_asset(
"tutorial-assets/stream-api/NASAs_Most_Scientifically_Complex_Space_Observatory_Requires_Precision-MP4_small.mp4"
)
设备可用性¶
StreamWriter
利用 FFmpeg 的 IO 抽象,将数据写入扬声器和 GUI 等媒体设备。
要写入设备,请将format
选项提供给StreamWriter
的构造函数。
不同的操作系统将有不同的设备选项,其可用性取决于 FFmpeg 的实际安装情况。
要检查哪些设备可用,可以使用ffmpeg -devices命令。
“audiotoolbox”(扬声器)和“sdl”(视频 GUI)可用。
$ ffmpeg -devices
...
Devices:
D. = Demuxing supported
.E = Muxing supported
--
E audiotoolbox AudioToolbox output device
D avfoundation AVFoundation input device
D lavfi Libavfilter virtual input device
E opengl OpenGL output
E sdl,sdl2 SDL2 output device
有关哪些设备在哪些操作系统上可用的详细信息,请查阅 FFmpeg 官方文档。https://ffmpeg.net.cn/ffmpeg-devices.html
播放音频¶
通过提供format="audiotoolbox"
选项,StreamWriter 将数据写入扬声器设备。
# Prepare sample audio
waveform, sample_rate = torchaudio.load(AUDIO_PATH, channels_first=False, normalize=False)
num_frames, num_channels = waveform.shape
# Configure StreamWriter to write to speaker device
s = StreamWriter(dst="-", format="audiotoolbox")
s.add_audio_stream(sample_rate, num_channels, format="s16")
# Write audio to the device
with s.open():
for i in range(0, num_frames, 256):
s.write_audio_chunk(0, waveform[i : i + 256])
注意
写入“audiotoolbox”是阻塞操作,但它不会等待音频播放。在播放音频时,设备必须保持打开状态。
以下代码将在音频写入后立即关闭设备,并在播放完成之前。添加time.sleep()
将有助于保持设备打开直到播放完成。
with s.open():
s.write_audio_chunk(0, waveform)
播放视频¶
要播放视频,可以使用format="sdl"
或format="opengl"
。同样,你需要一个启用了相应集成的 FFmpeg 版本。可用设备可以通过ffmpeg -devices
检查。
这里,我们使用 SDL 设备(https://ffmpeg.net.cn/ffmpeg-devices.html#sdl)。
# note:
# SDL device does not support specifying frame rate, and it has to
# match the refresh rate of display.
frame_rate = 120
width, height = 640, 360
因为我们定义了一个辅助函数,将视频加载委托给后台线程并提供数据块。
running = True
def video_streamer(path, frames_per_chunk):
import queue
import threading
from torchaudio.io import StreamReader
q = queue.Queue()
# Streaming process that runs in background thread
def _streamer():
streamer = StreamReader(path)
streamer.add_basic_video_stream(
frames_per_chunk, format="rgb24", frame_rate=frame_rate, width=width, height=height
)
for (chunk_,) in streamer.stream():
q.put(chunk_)
if not running:
break
# Start the background thread and fetch chunks
t = threading.Thread(target=_streamer)
t.start()
while running:
try:
yield q.get()
except queue.Empty:
break
t.join()
现在我们开始流式传输。按下“Q”将停止视频。
注意
针对 SDL 设备的write_video_chunk调用会阻塞,直到 SDL 完成视频播放。
# Set output device to SDL
s = StreamWriter("-", format="sdl")
# Configure video stream (RGB24)
s.add_video_stream(frame_rate, width, height, format="rgb24", encoder_format="rgb24")
# Play the video
with s.open():
for chunk in video_streamer(VIDEO_PATH, frames_per_chunk=256):
try:
s.write_video_chunk(0, chunk)
except RuntimeError:
running = False
break
[代码]
流媒体视频¶
到目前为止,我们已经了解了如何写入硬件设备。还有一些视频流的替代方法。
RTMP(实时消息协议)¶
使用 RTMP,你可以将媒体(视频和/或音频)流式传输到单个客户端。这不需要硬件设备,但需要一个单独的播放器。
要使用 RTMP,请在 StreamWriter 构造函数中将协议和路由指定为dst
参数,然后在打开目标时传入{"listen": "1"}
选项。
StreamWriter 将监听端口并等待客户端请求视频。open
的调用会阻塞直到收到请求。
s = StreamWriter(dst="rtmp://:1935/live/app", format="flv")
s.add_audio_stream(sample_rate=sample_rate, num_channels=num_channels, encoder="aac")
s.add_video_stream(frame_rate=frame_rate, width=width, height=height)
with s.open(option={"listen": "1"}):
for video_chunk, audio_chunk in generator():
s.write_audio_chunk(0, audio_chunk)
s.write_video_chunk(1, video_chunk)
[代码]
UDP(用户数据报协议)¶
使用 UDP,你可以将媒体(视频和/或音频)流式传输到套接字。这不需要硬件设备,但需要一个单独的播放器。
与 RTMP 不同,流式传输和客户端进程是分离的。流式传输进程不了解客户端进程。
s = StreamWriter(dst="udp://:48550", format="mpegts")
s.add_audio_stream(sample_rate=sample_rate, num_channels=num_channels, encoder="aac")
s.add_video_stream(frame_rate=frame_rate, width=width, height=height)
with s.open():
for video_chunk, audio_chunk in generator():
s.write_audio_chunk(0, audio_chunk)
s.write_video_chunk(1, video_chunk)
[代码]
脚本总运行时间: ( 0 分 0.000 秒)