Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert data from float64 to int16 in python 3?

Currently I am using soundfile to read audio data from a wav file like so:

import soundfile
raw_data, sample_rate = soundfile.read(filename)

Whilst I realise that you can select dtype=int16, I would like to know how to convert a float64 value to an int16 value (obviously there will be a loss of accuracy due to rounding, which is assumed to be acceptable).

like image 664
MichaelAndroidNewbie Avatar asked Feb 22 '26 16:02

MichaelAndroidNewbie


1 Answers

soundfile depends on numpy so I assume you have that installed already, then you can do something like this:

import numpy as np

# double-check your signal is in the range of -1..1
max_val = np.max(raw_data)
print(str(max_val))

# map to 16-bit
max_16bit = 2**15
raw_data = raw_data * max_16bit

# now change the data type
raw_data = raw_data.astype(np.int16)
like image 89
AudioDroid Avatar answered Feb 24 '26 15:02

AudioDroid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!