Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write 24-bit wav file using scipy or common alternative?

Frequently, wav files are or need to be 24-bit yet I do not see a way to write or read 24-bit wav files using scipy module. The documentation for wavfile.write() states that the resolution of the wav file is determined by the data type. That must mean 24-bit is not supported since I do not know of a 24-bit integer data type. If an alternative is necessary it would be nice if it were common so that files can be easily exchanged without the need for others with scipy to install 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))
like image 761
papahabla Avatar asked May 23 '13 16:05

papahabla


People also ask

Can a WAV file be 24-bit?

File Format: 24-bit/44.1k Sample Rate (or higher) WAV Files. Files uploaded to Bandcamp and SoundCloud can be 24-bit, and at higher sampler rates than 44.1k if available from the mastering engineer, which could make for better sound quality on the resulting data-compressed files such as mp3s.

How do I read a WAV file in Python?

Returns a namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname), equivalent to output of the get*() methods. Reads and returns at most n frames of audio, as a bytes object. Rewind the file pointer to the beginning of the audio stream. Following code reads some of the parameters of WAV file.

What is 24-bit WAV?

24-bit WAV is the purest form of audio available. It isn't any more "purer" than the 16 bit. There are no audible differences between them. It's just a bigger audio CONTAINER, that's all.


1 Answers

This is very easy using PySoundFile:

import soundfile as sf

x = ...
fs = ...

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

The conversion from floating point to PCM is done automatically.

See also my other answer.


UPDATE:

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

like image 186
Matthias Avatar answered Sep 28 '22 08:09

Matthias