Skip to content

Instantly share code, notes, and snippets.

@chiroptical
Created June 9, 2020 13:11
Show Gist options
  • Save chiroptical/460c495656a4318820e0aa8677262ee5 to your computer and use it in GitHub Desktop.
Save chiroptical/460c495656a4318820e0aa8677262ee5 to your computer and use it in GitHub Desktop.
Example Audio API
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/bmooreii/.local/lib/python3.7/site-packages/numba/errors.py:131: UserWarning: Insufficiently recent colorama version found. Numba requires colorama >= 0.3.9\n",
" warnings.warn(msg)\n"
]
}
],
"source": [
"from librosa import load\n",
"from soundfile import write"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"class Audio:\n",
" def __init__(self, samples, sample_rate):\n",
" self.samples = samples\n",
" self.sample_rate = sample_rate\n",
" \n",
" @classmethod\n",
" def from_file(cls, path, sample_rate=22050):\n",
" samples, sr = load(path, sr=sample_rate)\n",
" return cls(samples, sr)\n",
" \n",
" # from_bytesio -- for reading using Microsoft container\n",
" # other rarely used loading methods\n",
" \n",
" def trim(self, start_time, end_time):\n",
" start_sample = int(start_time * self.sample_rate)\n",
" end_sample = int(end_time * self.sample_rate)\n",
" samples_trimmed = self.samples[start_sample:end_sample]\n",
" return Audio(samples_trimmed, self.sample_rate)\n",
" \n",
" def save(self, fname):\n",
" write(fname, self.samples, self.sample_rate)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"audio = Audio.from_file(\"voice_ringing.wav\") \\\n",
" .trim(0, 1) \\\n",
" .save(\"second.wav\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment