[英]How to convert in-memory WebM audio file to mp3 audio file in Python?
我正在嘗試將 WebM 格式的音頻文件轉換為 MP3 文件。 由於服務器限制,我需要將這兩個文件都保存在內存中。 我嘗試使用 PyAv 來做到這一點,但在處理流后我無法接收 Python 文件類對象。 我的嘗試:
with av.open(webm_file, 'r') as inp:
f = SpooledTemporaryFile(mode="w+b")
with av.open(f, 'w', format="mpeg") as out:
out_stream = out.add_stream("mp3")
for frame in inp.decode(audio=0):
frame.pts = None
for packets in out_stream.encode(frame):
out.mux(packets)
for packets in out_stream.encode(None):
out.mux(packets)
webm_file 是 SpooledTemporaryFile 類型,但我不能像文件一樣獲得 outfile,有人可以幫忙嗎?
將format="mpeg"
替換為format="mp3"
。
mpeg
應用 MPEG-1 節目流,我們要創建mp3
容器格式。
mpeg
容器支持 mp3 編解碼器作為音頻流,但它不是我們要尋找的容器...
我想用"mp3"
替換"mpeg"
可以解決這個問題。
我不知道如何測試f = SpooledTemporaryFile(mode="w+b")
,所以我使用了輸入和輸出文件。
首先創建帶有合成音頻和視頻的 WebM 文件(使用 FFmpeg CLI)進行測試:
ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1 -f lavfi -i sine=frequency=100 -f lavfi -i sine=frequency=500 -map_channel 1.0.0 -map_channel 2.0.0 -vcodec libvpx-vp9 -crf 32 -acodec libopus -b:a 96K -ar 48000 -ac 2 -t 10s input.webm
使用 PyAV 在output.mp3
文件中將音頻通道從 opus 編解碼器轉碼為 mp3 編解碼器:
import av
#from tempfile import SpooledTemporaryFile
# Build input file for testing:
# ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1 -f lavfi -i sine=frequency=500 -f lavfi -i sine=frequency=800 -map_channel 1.0.0 -map_channel 2.0.0 -vcodec libvpx-vp9 -crf 32 -acodec libopus -b:a 96K -ar 48000 -ac 2 -t 10s input.webm
webm_file = "input.webm"
mp3_file = "output.mp3"
with av.open(webm_file, 'r') as inp:
#f = SpooledTemporaryFile(mode="w+b")
f = mp3_file
with av.open(f, 'w', format="mp3") as out: # Open file, setting format to mp3
out_stream = out.add_stream("mp3")
for frame in inp.decode(audio=0):
frame.pts = None
for packets in out_stream.encode(frame):
out.mux(packets)
for packets in out_stream.encode(None):
out.mux(packets)
MediaInfo 工具的輸出:
General
Complete name : C:\Tmp\output.mp3
Format : MPEG Audio
File size : 157 KiB
Duration : 10 s 32 ms
Overall bit rate mode : Variable
Overall bit rate : 128 kb/s
Writing library : LAME3.100
Audio
Format : MPEG Audio
Format version : Version 1
Format profile : Layer 3
Format settings : Joint stereo / MS Stereo
Duration : 10 s 32 ms
Bit rate mode : Variable
Bit rate : 128 kb/s
Channel(s) : 2 channels
Sampling rate : 48.0 kHz
Frame rate : 41.667 FPS (1152 SPF)
Compression mode : Lossy
Stream size : 157 KiB (100%)
Writing library : LAME3.100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.