import moviepy.editor as mp
#


from pylab import plot, show, title, xlabel, ylabel, subplot, savefig
from scipy import fft, arange, ifft
from numpy import sin, linspace, pi
from scipy.io.wavfile import read, write
import matplotlib.pyplot as plt
import peakutils
# clip = mp.VideoFileClip('/Users/schimmt/Pictures/GOPR1586.MP4').subclip(0)
# clip.audio.write_audiofile("../theaudioTest2.wav")

rate, data = read('../theaudioTest.wav')

def plotSpectru(y, Fs):
    n = len(y)  # lungime semnal
    k = arange(n)
    T = n / Fs
    frq = k / T  # two sides frequency range
    frq = frq[range(n / 2)]  # one side frequency range

    Y = fft(y) / n  # fft computing and normalization
    Y = Y[range(n / 2)]

    return frq, abs(Y)

# def findPeaks(pulse):
#     Peaks = peakutils.indexes(pulse, thres=0 * max(pulse))
#     return Peaks

y = data[:, 0]

fig, (ax1, ax2) = plt.subplots(2,1)



# lungime = len(y)
timp = len(y) / rate
t = linspace(0, timp, len(y))


ax1.plot(t, y)
ax1.set_xlabel('Time')
ax1.set_ylabel('Amplitude')

# Bits = findPeaks(y)
#
# print len(Bits)
# exit()
# for bits in Bits:
#     if bits == Bits[0]:
#         ax1.axvline(x=Bits[0], linewidth=.3, color='cyan', linestyle='-', label='$Starting Pulse$')
#
#     elif bits == Bits[2]:
#         ax1.axvline(x=Bits[2], linewidth=.3, color='purple', linestyle='-', label='$Exp. Run #$')
#     elif bits == Bits[12]:
#         ax1.axvline(x=Bits[12], linewidth=.3, color='green', linestyle='-', label='$Subj. ID$')
#
# for bits in range(len(Bits)):
#     ax1.axvline(x=Bits[bits], linewidth=.3, color='gray', linestyle='-')

frq, y = plotSpectru(y, rate)

ax2.set_xlim(0,1000)
ax2.set_ylim(0,1700)
ax2.plot(frq, y, 'r')  # plotting the spectrum
ax2.set_xlabel('Freq (Hz)')
ax2.set_ylabel('|Y(freq)|')
plt.show()