I created a sound this way :
import numpy as np
from scipy.io.wavfile import write
data=np.random.uniform(-1,-1,44100)
scaled=np.int8(data/np.max(np.abs(data))*127)
write('test8.wav',44100,scaled)
and I want to convert amplitudes using np.fromstring :
def tableau_ampli(filename) :
Monson = wave.open(filename,'r')
n = Monson.getnframes()
if Monson.getsampwidth() == 1 :
freq = np.fromstring(Monson.readframes(n),dtype=np.uint8)
print(freq)
for k in range(n):
if freq[k] > int(127) :
freq[k]=freq[k]-249
print(freq)
else :
freq = np.fromstring(Monson.readframes(n),dtype=np.uint16)
for k in range(len(freq)):
if freq[k]>32767 : # 32767 = [(2**16)/2]-1
freq[k]-=65536 # 65536 = 2**16
return(freq)
but it doesn't work when I execute tableau_ampli('test8.wav'). I think the problem is because
np.fromstring(Monson.readframes(n),dtype=np.uint8)
returns : [129 129 129 ..., 129 129 129]
and not an array or a string.
Can I get some help ?
This is happening because the elements in freq
are of uint8
, which gives us an unsigned integer from (0 to 255). See here.
So when you subtract something from it, let's say x
, it forces it into the range 0 to 255 by performing 256 - x
. Since 256 - 249 = 136, this is what you get.
You can change freq = np.fromstring(Monson.readframes(n),dtype=np.uint8)
to freq = np.fromstring(Monson.readframes(n),dtype=np.uint8).astype(int)
to convert it to an int data type and get -120.