8

通常,wav 文件是或需要是 24 位的,但我看不到使用 scipy 模块写入或读取 24 位 wav 文件的方法。wavfile.write() 的文档指出 wav 文件的分辨率由数据类型决定。这一定意味着不支持 24 位,因为我不知道 24 位整数数据类型。如果需要替代方案,那么如果它很常见,这样文件就可以轻松交换,而不需要其他使用 scipy 的人安装额外的模块。

import numpy as np
import scipy.io.wavfile as wavfile

fs=48000
t=1
nc=2
nbits=24
x = np.random.rand(t*fs,nc) * 2 - 1
wavfile.write('white.wav', fs, (x*(2**(nbits-1)-1)).astype(np.int32))
4

2 回答 2

4

这很容易使用PySoundFile

import soundfile as sf

x = ...
fs = ...

sf.write('white.wav', x, fs, subtype='PCM_24')

从浮点到 PCM 的转换是自动完成的。

另请参阅我的其他答案


更新:

sf.write()在 PySoundFile 版本 0.8.0 中,更改了参数顺序。现在文件名是第一位的,数据数组是第二个参数。我在上面的例子中改变了这一点。

于 2015-09-17T12:24:25.883 回答
0

我也遇到过这个问题。我有一个包含所有 32 位有符号样本的缓冲区,而在每个样本中,只使用 24 位(最高 8 位是 0 填充,即使数字为负数)。我的解决方案是:

    samples_4byte = self.buffer.tobytes()
    byte_format = ('%ds %dx ' % (3, 1)) * self.sample_len * 2
    samples_3byte = b''.join(struct.unpack(byte_format, samples_4byte))

现在我有一个可以写入波形文件的字节数组:

with wave.open(file_abs, 'wb') as wav_file:
        # Set the number of channels
        wav_file.setnchannels(2)
        # Set the sample width to 3 bytes
        wav_file.setsampwidth(3)
        # Set the frame rate to sample_rate
        wav_file.setframerate(self.sample_rate)
        # Set the number of frames to sample_len
        wav_file.setnframes(self.sample_len)
        # Set the compression type and description
        wav_file.setcomptype('NONE', "not compressed")
        # Write data
        wav_file.writeframes(samples_3byte)
于 2017-12-13T17:23:19.523 回答