#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 22:54:04 2018

@author: harshal
"""



## read a musical note
import numpy as np
from scipy.io import wavfile
from scipy.fftpack import fft
import matplotlib.pyplot as plt
#file = wave.open('/Volumes/DataSci/Data/HSCode/MusicAnalysis/createsound_amp50000.wav')
#nchannel = file.getnchannels()
#framerate = file.getframerate()
#nframes = file.getnframes()
#file.close()

framerate = 44100
fs, data = wavfile.read('/Volumes/DataSci/Data/HSCode/MusicAnalysis/Flute.nonvib.ff.A4.stereo.wav') # load the data

def findFrequencies(arr_data, i_framerate = 44100, i_top_n =5):
    a = arr_data.T[0] # this is a two channel soundtrack, I get the first track
#    b=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1)
    y = fft(a) # calculate fourier transform (complex numbers list)
    
    xf = np.linspace(0,int(framerate/2.0),int((framerate/2.0))+1) /4 # Need to find out this last /2 part
    yf = np.abs(y[:int((framerate//2.0))+1])
    
    plt.plot(xf,yf)
    
    yf_top_n = np.argsort(yf)[-i_top_n:][::-1]
    amp_top_n =  yf[yf_top_n] / np.max(yf[yf_top_n])
    freq_top_n = xf[yf_top_n]
    
    return freq_top_n, amp_top_n

top_freq , top_freq_amp = findFrequencies(data, i_framerate = 44100 , i_top_n = 10)

print('Frequencies: ',top_freq)
print('Amplitudes : ',top_freq_amp)


