I'm giving my code with few audio files which are not giving appropriate output. Code:
import numpy as np
import math
import wave
import os
import struct
def note_detect(audio_file):
Detected_Note = ""
beta = 1
max_notes = 100
sampling_freq = 38050
window_size = (sampling_freq / 37)
threshold = 600
array = [440.00, 130.8, 329.6, 196]
notes = ['A4', 'C3', 'E4', 'G3' ]
Identified_Notes = []
file_length = audio_file.getnframes()
sound = np.zeros(file_length)
for i in range(file_length):
data = audio_file.readframes(1)
data = struct.unpack("<h", data)
sound[i] = int(data[0])
sound = np.divide(sound, float(2**15))
sound_square = np.square(sound)
frequency = []
dft = []
i = 0
j = 0
k = 0
while(i<=len(sound_square)-window_size):
s = 0.0
j = 0
while(j<=window_size):
s = s + sound_square[i+j]
j = j + 1
if s < threshold:
if(i-k>window_size*4):
dft = np.array(dft)
dft = np.fft(sound[k:i])
dft=np.argsort(dft)
if(dft[0]>dft[-1] and dft[1]>dft[-1]):
i_max = dft[-1]
elif(dft[1]>dft[0] and dft[-1]>dft[0]):
i_max = dft[0]
else :
i_max = dft[1]
frequency.append((i_max*sampling_freq)/(i-k))
dft = []
k = i+1
i = i + window_size
print('length',len(frequency))
print("frequency")
for i in frequency :
print(i)
idx = (np.abs(array-i)).argmin()
Identified_Notes.append(notes[idx])
print(Identified_Notes)
Detected_Note=max(Identified_Notes,key=Identified_Notes.count)
return Detected_Note
if __name__ == "__main__":
path = os.getcwd()
file_name = path + "\Task_1.1_Audio_files\Audio_4.wav"
audio_file = wave.open(file_name)
Detected_Note = note_detect(audio_file)
print("\n\tDetected Note = " + str(Detected_Note))
x = raw_input("\n\tWant to check output for all Audio Files - Y/N: ")
if x == 'Y':
Detected_Note_list = []
file_count = len(os.listdir(path + "\Task_1.1_Audio_files"))
for file_number in range(1, file_count):
file_name = path + "\Task_1.1_Audio_files\Audio_"+str(file_number)+".wav"
audio_file = wave.open(file_name)
Detected_Note = note_detect(audio_file)
Detected_Note_list.append(Detected_Note)
print("\n\tDetected Notes = " + str(Detected_Note_list))
Audio files link: https://drive.google.com/open?id=1KVEQQUqBvwgDPf2JC_uQ0L6M_gzGDG6l
Respective output for Audio_6.wav is A4, for Audio_4.wav is E4,for Audio_5.wav is G3