从python读取wav文件并将帧转换为RAW s16le字符串 [英] Read wav file from python and convert frames into RAW s16le string

查看:434
本文介绍了从python读取wav文件并将帧转换为RAW s16le字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用librosa,wave或soundfile库中的Python读取文件,我需要将块(任何大小)推送到HTTP流.按照规范,流字符串输入要求我将帧转换为RAW s16le格式.

I'm reading a file in Python using either of librosa, wave or soundfile libraries and I need to push the chunk (any size) to a HTTP stream. By specification, stream string input requires me to convert frames into RAW s16le format.

我尝试了多种选择,包括:

I tried multiple options including:

soundarray,rate = librosa.load(pathToWavFile, dtype="<i2")
str = b''.join(soundarray)

但这只会创建一个空的音频流.我在做什么错了?

But this just creates an empty audio stream. What am I doing wrong?

推荐答案

您可以尝试

You can try pydub to convert audio to audio-segment, split audio-segment into chunks that are playable (i.e you can play each chunk), then convert them to raw as needed.

这是一个快速的代码.

Here is a quick code.

from pydub import AudioSegment
from pydub.utils import make_chunks

myaudio = AudioSegment.from_file("myaudio.wav" , "wav") 
chunk_length_ms = 1000 # pydub calculates in millisec
chunks = make_chunks(myaudio, chunk_length_ms) #Make chunks of one sec

#Convert chunks to raw audio data which you can then feed to HTTP stream
for i, chunk in enumerate(chunks):
    raw_audio_data = chunk.raw_data

默认原始音频为16位

>>> 
bytes_per_sample= 2  # 2 byte (16 bit) samples

由于raw_audio_data是原始格式,因此如果上述格式不起作用,则可以根据需要转换为任何其他格式.有关详细信息,请检查 pydub utils api .

Since raw_audio_data is raw, if above format doesn't work, you can convert to any other format as needed. Check pydub utils api for details.

这篇关于从python读取wav文件并将帧转换为RAW s16le字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆