{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Installing pydub\n\nSince, in this competition, Internet is not allowed, I've uploaded the latest version of `pydub` into [this](https://www.kaggle.com/gabrielmilan/pydub0241) dataset so we can install it and use it for converting MP3 audio into `numpy` arrays. Thanks for [Chris' explanation](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/113195) on how to do this.\n\nI've extracted the code from [this page](https://stackoverflow.com/questions/53633177/how-to-read-a-mp3-audio-file-into-a-numpy-array-save-a-numpy-array-to-mp3) on StackOverflow. Hope you enjoy.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"! pip install ../pydub0241/../input/pydub0241/pydub-0.24.1-py2.py3-none-any.whl","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Loading sample","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import pydub \nimport numpy as np\n\ndef read(f, normalized=False):\n    \"\"\"MP3 to numpy array\"\"\"\n    a = pydub.AudioSegment.from_mp3(f)\n    y = np.array(a.get_array_of_samples())\n    if a.channels == 2:\n        y = y.reshape((-1, 2))\n    if normalized:\n        return a.frame_rate, np.float32(y) / 2**15\n    else:\n        return a.frame_rate, y\n\ndef write(f, sr, x, normalized=False):\n    \"\"\"numpy array to MP3\"\"\"\n    channels = 2 if (x.ndim == 2 and x.shape[1] == 2) else 1\n    if normalized:  # normalized array - each item should be a float in [-1, 1)\n        y = np.int16(x * 2 ** 15)\n    else:\n        y = np.int16(x)\n    song = pydub.AudioSegment(y.tobytes(), frame_rate=sr, sample_width=2, channels=channels)\n    song.export(f, format=\"mp3\", bitrate=\"320k\")\n    \naudio_file = '../input/birdsong-recognition/train_audio/aldfly/XC134874.mp3'\nsr, x = read(audio_file)\n\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(16,10))\nplt.plot(x)\nplt.title(\"Sample MP3 loading into Numpy\")\nplt.show()","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}