Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
snakers4
GitHub Repository: snakers4/silero-vad
Path: blob/master/examples/colab_record_example.ipynb
1171 views
Kernel: Python 3

Dependencies and inputs

#!apt install ffmpeg !pip -q install pydub from google.colab import output from base64 import b64decode, b64encode from io import BytesIO import numpy as np from pydub import AudioSegment from IPython.display import HTML, display import torch import matplotlib.pyplot as plt import moviepy.editor as mpe from matplotlib.animation import FuncAnimation, FFMpegWriter import matplotlib matplotlib.use('Agg') torch.set_num_threads(1) model, _ = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad', force_reload=True) def int2float(audio): samples = audio.get_array_of_samples() new_sound = audio._spawn(samples) arr = np.array(samples).astype(np.float32) arr = arr / np.abs(arr).max() return arr AUDIO_HTML = """ <script> var my_div = document.createElement("DIV"); var my_p = document.createElement("P"); var my_btn = document.createElement("BUTTON"); var t = document.createTextNode("Press to start recording"); my_btn.appendChild(t); //my_p.appendChild(my_btn); my_div.appendChild(my_btn); document.body.appendChild(my_div); var base64data = 0; var reader; var recorder, gumStream; var recordButton = my_btn; var handleSuccess = function(stream) { gumStream = stream; var options = { //bitsPerSecond: 8000, //chrome seems to ignore, always 48k mimeType : 'audio/webm;codecs=opus' //mimeType : 'audio/webm;codecs=pcm' }; //recorder = new MediaRecorder(stream, options); recorder = new MediaRecorder(stream); recorder.ondataavailable = function(e) { var url = URL.createObjectURL(e.data); // var preview = document.createElement('audio'); // preview.controls = true; // preview.src = url; // document.body.appendChild(preview); reader = new FileReader(); reader.readAsDataURL(e.data); reader.onloadend = function() { base64data = reader.result; //console.log("Inside FileReader:" + base64data); } }; recorder.start(); }; recordButton.innerText = "Recording... press to stop"; navigator.mediaDevices.getUserMedia({audio: true}).then(handleSuccess); function toggleRecording() { if (recorder && recorder.state == "recording") { recorder.stop(); gumStream.getAudioTracks()[0].stop(); recordButton.innerText = "Saving recording..." } } // https://stackoverflow.com/a/951057 function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } var data = new Promise(resolve=>{ //recordButton.addEventListener("click", toggleRecording); recordButton.onclick = ()=>{ toggleRecording() sleep(2000).then(() => { // wait 2000ms for the data to be available... // ideally this should use something like await... //console.log("Inside data:" + base64data) resolve(base64data.toString()) }); } }); </script> """ def record(sec=10): display(HTML(AUDIO_HTML)) s = output.eval_js("data") b = b64decode(s.split(',')[1]) audio = AudioSegment.from_file(BytesIO(b)) audio.export('test.mp3', format='mp3') audio = audio.set_channels(1) audio = audio.set_frame_rate(16000) audio_float = int2float(audio) audio_tens = torch.tensor(audio_float) return audio_tens def make_animation(probs, audio_duration, interval=40): fig = plt.figure(figsize=(16, 9)) ax = plt.axes(xlim=(0, audio_duration), ylim=(0, 1.02)) line, = ax.plot([], [], lw=2) x = [i / 16000 * 512 for i in range(len(probs))] plt.xlabel('Time, seconds', fontsize=16) plt.ylabel('Speech Probability', fontsize=16) def init(): plt.fill_between(x, probs, color='#064273') line.set_data([], []) line.set_color('#990000') return line, def animate(i): x = i * interval / 1000 - 0.04 y = np.linspace(0, 1.02, 2) line.set_data(x, y) line.set_color('#990000') return line, anim = FuncAnimation(fig, animate, init_func=init, interval=interval, save_count=int(audio_duration / (interval / 1000))) f = r"animation.mp4" writervideo = FFMpegWriter(fps=1000/interval) anim.save(f, writer=writervideo) plt.close('all') def combine_audio(vidname, audname, outname, fps=25): my_clip = mpe.VideoFileClip(vidname, verbose=False) audio_background = mpe.AudioFileClip(audname) final_clip = my_clip.set_audio(audio_background) final_clip.write_videofile(outname,fps=fps,verbose=False) def record_make_animation(): tensor = record() print('Calculating probabilities...') speech_probs = [] window_size_samples = 512 speech_probs = model.audio_forward(tensor, sr=16000)[0].tolist() model.reset_states() print('Making animation...') make_animation(speech_probs, len(tensor) / 16000) print('Merging your voice with animation...') combine_audio('animation.mp4', 'test.mp3', 'merged.mp4') print('Done!') mp4 = open('merged.mp4','rb').read() data_url = "data:video/mp4;base64," + b64encode(mp4).decode() display(HTML(""" <video width=800 controls> <source src="%s" type="video/mp4"> </video> """ % data_url)) return speech_probs

Record example

speech_probs = record_make_animation()