How to read and write a 24-bit wav file using scipy or the usual alternative?

Often wav files should or should be 24-bit, but I see no way to write or read 24-bit wav files using the scipy module. The documentation for wavfile.write () states that the resolution of the wav file is determined by the data type. This means that 24-bit is not supported, since I do not know about a 24-bit integer data type. If an alternative is needed, it would be nice if it were common for the files to be easily exchanged without the need for others who did not have free space to install an additional module.

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
source share
2 answers

It is very simple using PySoundFile :

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

Conversion from floating point to PCM is performed automatically.

See also my other answer .


UPDATE:

In PySoundFile version 0.8.0, the order of the sf.write() arguments sf.write() been changed. Now the file name comes first, and the data array is the second argument. I changed this in the above example.

+3
source

I ran into this problem. I have a buffer containing all 32-bit signed samples, while in each example only 24 bits are used (the highest 8 bits are 0 additions, even if the number is negative). My decision:

  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)) 

Now I have a bytearray that can be written to the wave file:

 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) 

More importantly, I don’t want to wait for someone to fix the patch (like scipy) to complete my project.

0
source

Source: https://habr.com/ru/post/1482427/


All Articles