2

我正在尝试使用 88200 个样本转换 numpy.array 的音频采样率(从 44100 到 22050),其中我已经完成了一些过程(例如添加静音并转换为单声道)。我试图用它转换这个数组audioop.ratecv并且它可以工作,但是它返回一个 str 而不是一个 numpy 数组,当我写这些数据时scipy.io.wavfile.write,结果是一半的数据丢失了,音频速度是原来的两倍(而不是更慢,至少那会有点道理)。 audio.ratecv与 str 数组(例如wave.open返回)一起工作正常,但我不知道如何处理它们,所以我尝试从 str 转换为 numpy withnumpy.array2string(data)以将其传递给 ratecv 并获得正确的结果,然后再次转换为 numpy withnumpy.fromstring(data, dtype)现在 len 的数据是 8 个样本。我认为这是由于格式的复杂性,但我不知道如何控制它。我还没有弄清楚 str 会wave.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)
4

1 回答 1

0

经过更多研究后,我发现了我的错误,似乎 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

如果你发现有什么不对的地方,请随时纠正我,我还是一个学习者

于 2017-08-29T23:41:39.833 回答