音频数据字符串格式为 numpy 数组



我正在尝试转换具有 88200 个样本的 numpy.array 的音频采样率(从 44100 到 882000(,我已经在其中做了一些过程(例如添加静音并转换为单声道(。我尝试用audioop.ratecv转换这个数组并且可以工作,但它返回一个 str 而不是一个 numpy 数组,当我用scipy.io.wavfile.write写入这些数据时,结果是一半的数据丢失并且音频速度是两倍快(而不是更慢,至少这有点有意义(。audio.ratecv适用于 str 数组(例如wave.open返回(,但我不知道如何处理这些数组,所以我尝试使用numpy.array2string(data)从 str 转换为 numpy 以将其传递给 ratecv 并获得正确的结果,然后再次转换为 numpynumpy.fromstring(data, dtype)现在数据 len 是 8 个样本。我认为这是由于格式的复杂性,但我不知道如何控制它。我也没有弄清楚 strwave.open返回哪种格式,所以我可以强制对此进行格式化。

这是我代码的这一部分

def conv_sr(data, srold, fixSR, dType, chan = 1): 
state = None
width = 2 # numpy.int16
print "data shape", data.shape, type(data[0]) # returns shape 88200, type int16
fragments = numpy.array2string(data)
print "new fragments len", len(fragments), "type", type(fragments) # return len 30 type str
fragments_new, state = audioop.ratecv(fragments, width, chan, srold, fixSR, state)
print "fragments", len(fragments_new), type(fragments_new[0]) # returns 16, type str
data_to_return = numpy.fromstring(fragments_new, dtype=dType)
return data_to_return

我这样称呼它

data1 = numpy.array(data1, dtype=dType)
data_to_copy = numpy.append(data1, data2)
data_to_copy = _to_copy.sum(axis = 1) / chan
data_to_copy = data_to_copy.flatten() # because its mono
data_to_copy = conv_sr(data_to_copy, sr, fixSR, dType) #sr = 44100, fixSR = 22050
scipy.io.wavfile.write(filename, fixSR, data_to_copy)

经过更多的研究,我发现了我的错误,似乎 16 位音频是由两个 8 位"单元格"组成的,所以我穿的 dtype 是错误的,这就是我遇到音频速度问题的原因。我在这里找到了正确的 dtype。因此,在 conv_sr def 中,我传递了一个 numpy 数组,将其转换为数据字符串,传递它以转换采样率,再次转换为 numpy 数组以进行scipy.io.wavfile.write,最后,将 2 8 位转换为 16 位格式

def widthFinder(dType):
try:
b = str(dType)
bits = int(b[-2:])
except:
b = str(dType)
bits = int(b[-1:])
width = bits/8
return width
def conv_sr(data, srold, fixSR, dType, chan = 1): 
state = None
width = widthFinder(dType)
if width != 1 and width != 2 and width != 4:
width = 2
fragments = data.tobytes()
fragments_new, state = audioop.ratecv(fragments, width, chan, srold, fixSR, state)
fragments_dtype = numpy.dtype((numpy.int16, {'x':(numpy.int8,0), 'y':(numpy.int8,1)}))
data_to_return = numpy.fromstring(fragments_new, dtype=fragments_dtype)
data_to_return = data_to_return.astype(dType)
return data_to_return

如果您发现任何错误,请随时纠正我,我仍然是学习者

最新更新