{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"markdown","source":"### In this notebook,I have performed basic audio analysis using Scipy and I have used Pydub for quick format conversion as scipy only work with .wav format. I have used scipy over librosa or pyAudioAnalysis as it is very basic and effective package for mathematical computations. ","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"!pip install pydub","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nimport scipy.io.wavfile\nimport matplotlib.pyplot as plt\nfrom pydub import AudioSegment as read\nfrom scipy.fftpack import fft,fftfreq","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"audio = read.from_mp3('/kaggle/input/birdsong-recognition/train_audio/nutwoo/XC462016.mp3')\naudio.export(\"file.wav\", format=\"wav\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Listen to the audio clip\")\naudio","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sampling_rate,data = scipy.io.wavfile.read(\"file.wav\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Sampling rate of the audio signal:\",sampling_rate)\nprint(\"Number of data points:\",len(data))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Sampling rate of this audio signal is 44100 Hz or 44.1 KHz which is a standard value of sampling rate as per the Nquist theorem for human hearing range. Higher the sampling rate better is the sound quality. Dividing the number of data points by the sampling rate gives the length of the track in seconds.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Length of the audio clip in seconds:\",len(data)/sampling_rate)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Energy of a signal\n\nAn important metric for signal analysis can be the **Energy** of the signal which defines its actual strength.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Energy of the audio signal : {:e}\".format(np.sum(data.astype(float)**2)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Waveplot of the audio signal","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"time = np.arange(0, float(data.shape[0]), 1) / sampling_rate\n\nplt.figure(figsize=(14, 6))\nplt.plot(time,data)\nplt.xlabel('Time (s)')\nplt.ylabel('Amplitude')\nplt.title('Waveplot')\nplt.grid(True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"### Fourier Analysis\n\nProcess of decomposing a function into osicillatory components is known as Fourier analysis. In signal processing context,Fourier analysis helps in determining which frequencies are present in the signal.\n\nIn the context of bird call identification problem, **Fourier analysis can help in differentiating the actual bird sounds and the ambient noise present in the audio signal by differentiating in the frequencies and using the fourier transform as feature for sound classification**. ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Get the absolute value of real and complex components\nf_components = abs(fft(data))\n\n# frequencies\nfreqs = fftfreq(data.shape[0],1/sampling_rate)\n\nplt.figure(figsize=(8, 6))\nplt.xlim( [10, sampling_rate/2] )\nplt.xscale( 'log' )\nplt.grid( True )\nplt.xlabel( 'Frequency (Hz)' )\nplt.title('FFT of the audio signal')\nplt.plot(freqs[:int(freqs.size/2)],f_components[:int(freqs.size/2)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n = len(data)\nf_components = f_components[0:(int(n/2))]\n\n# scale by the number of points so that the magnitude does not depend on the length\nf_components = f_components / float(n)\n\n#calculate the frequency at each point in Hz\nfreqArray = np.arange(0, (n/2), 1.0) * (sampling_rate*1.0/n);\n\nplt.figure(figsize=(8, 6))\nplt.plot(freqArray/1000, 10*np.log10(f_components), linewidth=0.1)\nplt.get_cmap('autumn_r')\nplt.title('Power-Frequency Spectrum')\nplt.xlabel('Frequency (kHz)')\nplt.ylabel('Power (dB)')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Spectral Analysis\n\nSpectral analysis of the audio signal represents the spectrum of frequencies as it varies with time.It is useful in knowing the intensity of the sound w.r.t the frequency and time elapsed.\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"pgram, freqs, bins, im = plt.specgram(data, Fs=sampling_rate, NFFT=1024, cmap=plt.get_cmap('autumn_r'))\ncbar=plt.colorbar(im)\nplt.xlabel('Time (s)')\nplt.ylabel('Frequency (Hz)')\ncbar.set_label('Intensity dB')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The result we got allows us to pick a certain frequency and examine it for better understanding. For example we can take 12.53 KHZ for further examination.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"index = np.where(freqs==12532.32421875)\nsegment =pgram[index[0][0],:]\nplt.plot(bins,segment, color='#ff7f00')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Train Data EDA","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/birdsong-recognition/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}