'''
reads wav file
http://soundfile.sapp.org/doc/WaveFormat/
https://blogs.msdn.microsoft.com/dawate/2009/06/23/intro-to-audio-programming-part-2-demystifying-the-wav-format/
'''
import numpy as np #for 2d array
def read_data(name):
    with open(name, "rb") as f:
        sGroupID1 = f.read(4).decode('ascii') #always RIFF
        dwFileLength = int.from_bytes(f.read(4), byteorder='little') #file size minus 8 in bytes
        sRiffType = f.read(4).decode('ascii') #always "WAVE"
        sGroupID2 = f.read(4).decode('ascii') #always "fmt "
        dwHeaderChunkSize = int.from_bytes(f.read(4), byteorder='little') #size of next header section in bytes
        subchunk = f.read(dwHeaderChunkSize) #reads the section above
        wFormatTag = int.from_bytes(subchunk[:2], byteorder='little') #always 1 for PCM files (basically everything)
        wChannels = int.from_bytes(subchunk[2:4], byteorder='little') #amount of channels (1 = mono, 2 stereo...)
        dwSamplesPerSec = int.from_bytes(subchunk[4:8], byteorder='little') #samples taken per sec [Hz]
        dwAvgBytesPerSec = int.from_bytes(subchunk[8:12], byteorder='little') #amount of bytes/ sec, useful for mem allocation
        wBlockAlign = int.from_bytes(subchunk[12:14], byteorder='little') #amount of bytes for a sample*channels
        dwBitsPerSample = int.from_bytes(subchunk[14:16], byteorder='little') #bits per sample (8 = 8bit song, 16 = 2byte...)
        extraParams = subchunk[16:] #stores extra parameters
        sGroupID3 = f.read(4).decode('ascii') #always "data"
        dwChunkSize = int.from_bytes(f.read(4), byteorder='little') #size of data field in bytes

        data = f.read(dwChunkSize) #reads data field, stores in bytes datatype
        sound = np.zeros((wChannels, dwChunkSize//wChannels)) #creates numpy array. y size = n channels; x size = n of samples
        j = 0 #j cycles between channels
        for i in range(dwChunkSize//(dwBitsPerSample//8)):
            sound[j][(i//wChannels)] = int.from_bytes(data[i:i+dwBitsPerSample//8], byteorder='little')
            #j selects channel; i/channels tells y position !integer division, decimals cut!
            j += 1
            j = j % wChannels #when j= n of channels, resets back to 0
        #print(sound) #debug
        return sound
