0

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 ?

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • `[129 129 129 ..., 129 129 129]` is an array of `uint8`, just as you specified. – hpaulj Apr 26 '17 at 16:48
  • but why can't I edit it ? when I execute for k in range(n): if freq[k] > int(127) : freq[k]=freq[k]-249 print(freq) However when I execute it on : array([129,129,129,129,129,129]) it does work :/ – Anouar Brahimi Apr 26 '17 at 16:57
  • What is `wave` in the first line in `tableau_ampli()`? When I try running this snippet, it gives me an error there. – Antimony Apr 27 '17 at 22:43
  • can you be more specific about what is not working? Do you get an error? Or an undesired result? What do you expect instead? – Antimony Apr 27 '17 at 22:44
  • It returns : array([136, 136, 136, ..., 136, 136, 136], dtype=uint8) however, it is supposed to return : array([-120, -120, -120, ..., -120, -120, -120], dtype=uint8) – Anouar Brahimi Apr 28 '17 at 10:35
  • you should first : import wave – Anouar Brahimi Apr 28 '17 at 10:48

1 Answers1

0

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.

Antimony
  • 2,230
  • 3
  • 28
  • 38