"""
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Free-Sound-Cloud-Audio-Classification-Challange">Free Sound Cloud Audio Classification Challange<a class="anchor-link" href="https://www.kaggle.com/ashishpatel26/audio-classification?scriptVersionId=12940645#Free-Sound-Cloud-Audio-Classification-Challange" target="_self">¶</a></h1><p><img src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Freesound_project_website_logo.png" alt=""></p>
<h1 style="text-align:center;"> Project Model</h1><p>Input file : <strong>Audio Wave file</strong><br>
Output file : <strong>Label</strong>
<img src="https://storage.googleapis.com/kaggle-media/competitions/freesound/task2_freesound_audio_tagging.png" alt=""></p>

</div>
</div>
</div>
"""
"""
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><ul class="toc-item"><li><span><a href="#Loading-an-audio-file" data-toc-modified-id="Loading-an-audio-file-0.1"><span class="toc-item-num">0.1&nbsp;&nbsp;</span>Loading an audio file</a></span></li><li><span><a href="#Playing-Audio" data-toc-modified-id="Playing-Audio-0.2"><span class="toc-item-num">0.2&nbsp;&nbsp;</span>Playing Audio</a></span></li><li><span><a href="#Visualizing-Audio" data-toc-modified-id="Visualizing-Audio-0.3"><span class="toc-item-num">0.3&nbsp;&nbsp;</span>Visualizing Audio</a></span><ul class="toc-item"><li><span><a href="#Waveform" data-toc-modified-id="Waveform-0.3.1"><span class="toc-item-num">0.3.1&nbsp;&nbsp;</span>Waveform</a></span></li><li><span><a href="#Spectrogram" data-toc-modified-id="Spectrogram-0.3.2"><span class="toc-item-num">0.3.2&nbsp;&nbsp;</span>Spectrogram</a></span></li><li><span><a href="#Log-Frequency-axis" data-toc-modified-id="Log-Frequency-axis-0.3.3"><span class="toc-item-num">0.3.3&nbsp;&nbsp;</span>Log Frequency axis</a></span></li></ul></li><li><span><a href="#Creating-an-audio-signal" data-toc-modified-id="Creating-an-audio-signal-0.4"><span class="toc-item-num">0.4&nbsp;&nbsp;</span>Creating an audio signal</a></span></li><li><span><a href="#Playing-the-sound" data-toc-modified-id="Playing-the-sound-0.5"><span class="toc-item-num">0.5&nbsp;&nbsp;</span>Playing the sound</a></span></li><li><span><a href="#Saving-the-signal" data-toc-modified-id="Saving-the-signal-0.6"><span class="toc-item-num">0.6&nbsp;&nbsp;</span>Saving the signal</a></span></li></ul></li><li><span><a href="#Feature-Extraction" data-toc-modified-id="Feature-Extraction-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Feature Extraction</a></span><ul class="toc-item"><li><span><a href="#1.-Zero-Crossing-Rate" data-toc-modified-id="1.-Zero-Crossing-Rate-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>1. Zero Crossing Rate</a></span></li><li><span><a href="#2.Spectral-Centroid" data-toc-modified-id="2.Spectral-Centroid-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>2.Spectral Centroid</a></span></li><li><span><a href="#3.Spectral-Rolloff" data-toc-modified-id="3.Spectral-Rolloff-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>3.Spectral Rolloff</a></span></li><li><span><a href="#4.MFCC" data-toc-modified-id="4.MFCC-1.4"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>4.MFCC</a></span></li><li><span><a href="#Feature-Scaling" data-toc-modified-id="Feature-Scaling-1.5"><span class="toc-item-num">1.5&nbsp;&nbsp;</span>Feature Scaling</a></span></li><li><span><a href="#Chroma-Frequencies" data-toc-modified-id="Chroma-Frequencies-1.6"><span class="toc-item-num">1.6&nbsp;&nbsp;</span>Chroma Frequencies</a></span></li></ul></li></ul></div>
"""
"""
## Loading an audio file
"""
import warnings
warnings.filterwarnings('ignore')
import librosa
audio_path = '../input/train_curated/0006ae4e.wav'
x , sr = librosa.load(audio_path)
"""
## Playing Audio
Using IPython.display.Audio, to play the audio
"""
import IPython.display as ipd
ipd.Audio(audio_path)
"""
You can even use an mp3 or a WMA format for the audio example.
"""
"""
## Visualizing Audio

### Waveform
We can plot the audio array using librosa.display.waveplot:

"""
%matplotlib inline
import sklearn
import matplotlib.pyplot as plt
import librosa.display

plt.figure(figsize=(20, 5))
librosa.display.waveplot(x, sr=sr)
"""
Here, we have the plot the amplitude envelope of a waveform.
"""
"""
### Spectrogram
We can also display a spectrogram using librosa.display.specshow.
"""
X = librosa.stft(x)
Xdb = librosa.amplitude_to_db(abs(X))
plt.figure(figsize=(20, 5))
librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')
plt.colorbar()
"""
### Log Frequency axis
"""
librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='log')
plt.colorbar()
"""
## Creating an audio signal
Let us now create an audio signal at 220Hz. We know an audio signal is a numpy array, so we shall create one and pass it on to the audio function.

"""
import numpy as np
sr = 22050 # sample rate
T = 5.0    # seconds
t = np.linspace(0, T, int(T*sr), endpoint=False) # time variable
x = 0.5*np.sin(2*np.pi*220*t)# pure sine wave at 220 Hz

"""
## Playing the sound

"""
ipd.Audio(x, rate=sr) # load a NumPy array
"""
## Saving the signal

"""
librosa.output.write_wav('../tone_440.wav', x, sr) # writing wave file in tone440.wav format
"""
# Feature Extraction
"""
x, sr = librosa.load('../input/train_noisy/000b6cfb.wav')
ipd.Audio(x, rate=sr)
#Plot the signal:
plt.figure(figsize=(20, 5))
librosa.display.waveplot(x, sr=sr)
"""
## 1. Zero Crossing Rate
"""
# Zooming in
n0 = 9000
n1 = 9100
plt.figure(figsize=(20, 5))
plt.plot(x[n0:n1])
plt.grid()
"""
I count 6 zero crossings. Let's compute the zero crossings using librosa.
"""
zero_crossings = librosa.zero_crossings(x[n0:n1], pad=False)
zero_crossings.shape
print(sum(zero_crossings))
"""
## 2.Spectral Centroid
"""
spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]
spectral_centroids.shape
# Computing the time variable for visualization
plt.figure(figsize=(20,5))
frames = range(len(spectral_centroids))
t = librosa.frames_to_time(frames)

# Normalising the spectral centroid for visualisation
def normalize(x, axis=0):
    return sklearn.preprocessing.minmax_scale(x, axis=axis)

#Plotting the Spectral Centroid along the waveform
librosa.display.waveplot(x, sr=sr, alpha=0.4)
plt.plot(t, normalize(spectral_centroids), color='r')
"""
## 3.Spectral Rolloff 
"""
plt.figure(figsize=(20,5))
spectral_rolloff = librosa.feature.spectral_rolloff(x+0.01, sr=sr)[0]
librosa.display.waveplot(x, sr=sr, alpha=0.4)
plt.plot(t, normalize(spectral_rolloff), color='r')
plt.grid()
"""
## 4.MFCC
"""
plt.figure(figsize=(20,5))
x, fs = librosa.load('../input/train_curated/0006ae4e.wav')
librosa.display.waveplot(x, sr=sr)
# MFCC
plt.figure(figsize=(20,5))
mfccs = librosa.feature.mfcc(x, sr=sr)
print(mfccs.shape)

librosa.display.specshow(mfccs, sr=sr, x_axis='time')
"""
## Feature Scaling
Let's scale the MFCCs such that each coefficient dimension has zero mean and unit variance:
"""
mfccs = sklearn.preprocessing.scale(mfccs, axis=1)
print(mfccs.mean(axis=1))
print(mfccs.var(axis=1))
plt.figure(figsize=(20,8))
librosa.display.specshow(mfccs, sr=sr, x_axis='time')
"""
## Chroma Frequencies
"""
# Loadign the file
x, sr = librosa.load('../input/train_curated/0006ae4e.wav')
ipd.Audio(x, rate=sr)
hop_length = 512
chromagram = librosa.feature.chroma_stft(x, sr=sr, hop_length=hop_length)
plt.figure(figsize=(15, 5))
librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', hop_length=hop_length, cmap='coolwarm')