我正在从URL下载的WAV音频中读取字节。我想将这些字节“重构”为.wav文件。我尝试了下面的代码,但是生成的文件几乎是静态的。例如,当我下载自己讲话的音频时,生成的.wav文件仅是静态的,但是当我知道音频应该播放我的声音时,我可以听到轻微的更改/失真。我在做什么错了?
from pprint import pprint
import scipy.io.wavfile
import numpy
#download a wav audio recording from a url
>>>response = client.get_recording(r"someurl.com")
>>>pprint(response)
(b'RIFFv\xfc\x03\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x80>\x00\x00'
...
b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
...
b'\xea\xff\xfd\xff\x10\x00\x0c\x00\xf0\xff\x06\x00\x10\x00\x06\x00'
...)
>>>a=bytearray(response)
>>>pprint(a)
bytearray(b'RIFFv\xfc\x03\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00'
b'\x80>\x00\x00\x00}\x00\x00\x02\x00\x10\x00LISTJ\x00\x00\x00INFOINAM'
b'0\x00\x00\x00Conference d95ac842-08b7-4380-83ec-85ac6428cc41\x00'
b'IART\x06\x00\x00\x00Nexmo\x00data\x00\xfc\x03\x00\xff\xff'
b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
...
b'\x12\x00\xf6\xff\t\x00\xed\xff\xf6\xff\xfc\xff\xea\xff\xfd\xff'
...)
>>>b = numpy.array(a, dtype=numpy.int16)
>>>pprint(b)
array([ 82, 73, 70, ..., 255, 248, 255], dtype=int16)
>>>scipy.io.wavfile.write(r"C:\Users\somefolder\newwavfile.wav",
16000, b)
答案 0 :(得分:3)
当您有连续的字节流时,AudioSegment.from_raw()也将起作用:
import io
from pydub import AudioSegment
current_data定义为您收到的字节流
s = io.BytesIO(current_data)
audio = AudioSegment.from_raw(s, sample_width, frame_rate, channels).export(filename, format='wav')
答案 1 :(得分:2)
您可以简单地将response
中的数据写入文件:
with open('myfile.wav', mode='bx') as f:
f.write(response)
如果您想以NumPy数组的形式访问音频数据而不先将其写入文件,则可以使用soundfile模块,如下所示:
import io
import soundfile as sf
data, samplerate = sf.read(io.BytesIO(response))
另请参见以下示例:https://pysoundfile.readthedocs.io/en/0.9.0/#virtual-io
答案 2 :(得分:2)
将波形文件头添加到原始音频字节(从波形库中提取):
def index(request):
form = WordForm(request.POST)
if form.is_valid():
word1 = form.cleaned_data['Word1']
word2 = form.cleaned_data['Word2']
word3 = form.cleaned_data['Word3']
result = form.cleaned_data['Result']
else:
word1 = word2 = word3 = result = None
context = {'form': form, 'word1': word1, 'word2': word2, 'word3': word3, 'result': result}
return render(request, 'form.html', context)