-
Notifications
You must be signed in to change notification settings - Fork 0
/
song_and_lyric_generator.py
2579 lines (2131 loc) · 65.6 KB
/
song_and_lyric_generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Song and Lyric Generator.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ey676qv3HAKVVXyVGNfnKiYOjvdpC3Dk
# Setup
```
Please read the runprogram.txt file if you are running this program on your local disk.
If you have any issues, please contact us at [email protected]
```
"""
#audio
import os
import socket
import threading
import IPython
import portpicker
from six.moves import SimpleHTTPServer
from six.moves import socketserver
from google.colab import output
class _V6Server(socketserver.TCPServer):
address_family = socket.AF_INET6
class _FileHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""SimpleHTTPRequestHandler with a couple tweaks."""
def translate_path(self, path):
# Client specifies absolute paths.
return path
def log_message(self, fmt, *args):
# Suppress logging since it's on the background. Any errors will be reported
# via the handler.
pass
def end_headers(self):
# Do not cache the response in the notebook, since it may be quite large.
self.send_header('x-colab-notebook-cache-control', 'no-cache')
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def play_audio(filename):
"""Downloads the file to the user's local disk via a browser download action.
Args:
filename: Name of the file on disk to be downloaded.
"""
started = threading.Event()
port = portpicker.pick_unused_port()
def server_entry():
httpd = _V6Server(('::', port), _FileHandler)
started.set()
# Serve multiple requests, in case the audio is played more than once.
httpd.serve_forever()
thread = threading.Thread(target=server_entry)
thread.start()
started.wait()
output.eval_js("""
(()=> {
const audio = document.createElement('audio');
audio.controls = true;
audio.autoplay = true;
audio.src = `https://localhost:%(port)d%(path)s`;
document.body.appendChild(audio);
})()
"""% {'port': port, 'path': os.path.abspath(filename)})
!pip install ffmpeg-python
from IPython.display import HTML, Audio
from google.colab.output import eval_js
from base64 import b64decode
import numpy as np
from scipy.io.wavfile import read as wav_read
import io
import ffmpeg
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 the recording... pls wait!"
}
}
// 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 get_audio():
display(HTML(AUDIO_HTML))
data = eval_js("data")
binary = b64decode(data.split(',')[1])
process = (ffmpeg
.input('pipe:0')
.output('pipe:1', format='wav')
.run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)
)
output, err = process.communicate(input=binary)
riff_chunk_size = len(output) - 8
# Break up the chunk size into four bytes, held in b.
q = riff_chunk_size
b = []
for i in range(4):
q, r = divmod(q, 256)
b.append(r)
# Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.
riff = output[:4] + bytes(b) + output[8:]
sr, audio = wav_read(io.BytesIO(riff))
return audio, sr
print("LYRIC GENERATOR")
print("---------------")
print("Coded by Kendall")
print(
)
print(
'''
MENU
1. MrBeast6000 - Theme Song
2. We Are The Champions - Queen
3. Don't Stop Me Now - Queen
4. Hey Jude - The Beatles
5. Let it Be - The Beatles
6. Bohemian Rhapsody - Queen
7. Imagine - John Lennon
8. Radio / Video - System Of A Down
9. Never Gonna Give You Up - Rick Astley
10. Hide and Seek - Imogen Heap
Hope you have fun using this Lyric Generator
'''
)
"""# Lyrics and Song Generator
"""
print("Want the lyrics and audio of MrBeast6000 by Theme ?")
print("Type yes on your keyboard if you would like to get the lyrics and audio of MrBeast's Theme Song.")
if input(""):
print(
'''
[Chorus]
MrBeast6000, oh
MrBeast6000, oh
[Verse 1]
MrBeast6000, yeah, you know his name
He changed it once or twice, but I think it's here to stay
His thumbnails were made in Paint
But if you ask me, I think they're kind of quaint
[Chorus]
MrBeast6000, oh
MrBeast6000, oh
[Verse 2]
His random videos are the name of the game
Some might say they're his ticket to fame
The occasional intro may not make sense
But we all get a laugh at their expense
[Chorus]
MrBeast6000, oh
MrBeast6000, oh
[Outro]
MrBeast, oh
MrBeast, oh
MrBeast, oh
MrBeast, oh, 6000
MrBeast 6000
'''
)
#play sound
from IPython.display import Audio
play_audio('/content/drive/MyDrive/songs/1.mp3')
print("Please wait while the audio file loads and then press play for the audio to play!")
print("Lyrics and Song Generated")
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
#singsong
print("You may sing along with the audio and lyrics or sing the song yourself after playing the audio, If your not interested, you may please skip to the next code block without inputting anything")
print("Please type any key to begin the sing along/sing alone!")
print("If you are interested and you input anything, it's pretty self-explanatory from there!.")
if input(""):
"""
To write this piece of code I took inspiration/code from a lot of places.
It was late night, so I'm not sure how much I created or just copied o.O
Here are some of the possible references:
https://blog.addpipe.com/recording-audio-in-the-browser-using-pure-html5-and-minimal-javascript/
https://stackoverflow.com/a/18650249
https://hacks.mozilla.org/2014/06/easy-audio-capture-with-the-mediarecorder-api/
https://air.ghost.io/recording-to-an-audio-file-using-html5-and-js/
https://stackoverflow.com/a/49019356
"""
from IPython.display import HTML, Audio
from google.colab.output import eval_js
from base64 import b64decode
import numpy as np
from scipy.io.wavfile import read as wav_read
import io
import ffmpeg
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 the recording... pls wait!"
}
}
// 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 get_audio():
display(HTML(AUDIO_HTML))
data = eval_js("data")
binary = b64decode(data.split(',')[1])
process = (ffmpeg
.input('pipe:0')
.output('pipe:1', format='wav')
.run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)
)
output, err = process.communicate(input=binary)
riff_chunk_size = len(output) - 8
# Break up the chunk size into four bytes, held in b.
q = riff_chunk_size
b = []
for i in range(4):
q, r = divmod(q, 256)
b.append(r)
# Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.
riff = output[:4] + bytes(b) + output[8:]
sr, audio = wav_read(io.BytesIO(riff))
return audio, sr
audio, sr = get_audio()
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(audio)
plt.show()
print("Done! You may play your recording or go to the next code block.")
print("Would you like lyrics and audio for another song. Type Yes to continue")
if input(""):
print("Want the lyrics and audio of We Are The Champions by Queen?")
print("Type any key on your keyboard if you would like to get the lyrics and audio of We Are The Champions by Queen.")
if input(""):
print(
'''
I've paid my dues
Time after time.
I've done my sentence
But committed no crime.
And bad mistakes‒
I've made a few.
I've had my share of sand kicked in my face
But I've come through.
And I need to go on and on, and on, and on.
We are the champions, my friends.
And we'll keep on fighting 'til the end.
We are the champions.
We are the champions.
No time for losers
'Cause we are the champions of the world.
I've taken my bows,
And my curtain calls.
You brought me fame and fortune, and everything that goes with it.
I thank you all.
But it's been no bed of roses,
No pleasure cruise.
I consider it a challenge before the whole human race,
And I ain't gonna lose.
And I need just go on and on, and on, and on.
We are the champions, my friends.
And we'll keep on fighting 'til the end.
We are the champions.
We are the champions.
No time for losers
'Cause we are the champions of the world.
We are the champions, my friends,
And we'll keep on fighting 'til the end.
We are the champions.
We are the champions.
No time for losers
'Cause we are the champions.
'''
)
#play sound
from IPython.display import Audio
play_audio('/content/drive/MyDrive/songs/2.mp3')
print("Please wait while the audio file loads and then press play for the audio to play!")
print("Lyrics and Song Generated")
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
#singsong
print("You may sing along with the audio and lyrics or sing the song yourself after playing the audio, If your not interested, you may please skip to the next code block without inputting anything")
print("Please type any key to begin the sing along/sing alone!")
print("If you are interested and you input anything, it's pretty self-explanatory from there!.")
if input(""):
"""
To write this piece of code I took inspiration/code from a lot of places.
It was late night, so I'm not sure how much I created or just copied o.O
Here are some of the possible references:
https://blog.addpipe.com/recording-audio-in-the-browser-using-pure-html5-and-minimal-javascript/
https://stackoverflow.com/a/18650249
https://hacks.mozilla.org/2014/06/easy-audio-capture-with-the-mediarecorder-api/
https://air.ghost.io/recording-to-an-audio-file-using-html5-and-js/
https://stackoverflow.com/a/49019356
"""
from IPython.display import HTML, Audio
from google.colab.output import eval_js
from base64 import b64decode
import numpy as np
from scipy.io.wavfile import read as wav_read
import io
import ffmpeg
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 the recording... pls wait!"
}
}
// 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 get_audio():
display(HTML(AUDIO_HTML))
data = eval_js("data")
binary = b64decode(data.split(',')[1])
process = (ffmpeg
.input('pipe:0')
.output('pipe:1', format='wav')
.run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)
)
output, err = process.communicate(input=binary)
riff_chunk_size = len(output) - 8
# Break up the chunk size into four bytes, held in b.
q = riff_chunk_size
b = []
for i in range(4):
q, r = divmod(q, 256)
b.append(r)
# Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.
riff = output[:4] + bytes(b) + output[8:]
sr, audio = wav_read(io.BytesIO(riff))
return audio, sr
audio, sr = get_audio()
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(audio)
plt.show()
print("Done! You may play your recording or go to the next code block.")
print("Would you like lyrics and audio for another song. Type Yes to continue")
if input(""):
print("Do you want to lyrics and audio of Don't Stop Me Now by Queen?")
print("Type any key on your keyboard if you want the lyrics and audio of Don't Stop Me Now by Queen.")
if input(""):
print(
'''
[Intro]
Tonight I'm gonna have myself a real good time
I feel alive
And the world, I'll turn it inside out, yeah
I'm floating around in ecstasy
So (Don't stop me now)
(Don't stop me)
'Cause I'm having a good time
Having a good time
[Verse 1]
I'm a shooting star leaping through the sky like a tiger
Defying the laws of gravity
I'm a racing car passing by like Lady Godiva
I'm gonna go, go, go, there's no stopping me
[Pre-Chorus]
I'm burning through the sky, yeah
Two hundred degrees, that's why they call me Mister Fahrenheit
I'm travelling at the speed of light
I wanna make a supersonic man outta you
[Chorus]
(Don't stop me now)
I'm having such a good time
I'm having a ball
(Don't stop me now)
If you wanna have a good time
Just give me a call
(Don't stop me now)
'Cause I'm having a good time
(Don't stop me now)
Yes, I'm having a good time
I don't wanna stop at all, yeah
[Verse 2]
I'm a rocket ship on my way to Mars on a collision course
I am a satellite, I'm out of control
I'm a sex machine ready to reload like an atom bomb
About to oh, oh, oh, oh, oh, explode
[Pre-Chorus]
I'm burning through the sky, yeah
Two hundred degrees, that's why they call me Mister Fahrenheit
I'm travelling at the speed of light
I wanna make a supersonic woman of you
[Bridge]
(Don't stop me, don't stop me, don't stop me)
Hey, hey, hey
(Don't stop me, don't stop me, ooh, ooh, ooh)
I like it
(Don't stop me, don't stop me)
Have a good time, good time
(Don't stop me, don't stop me) Woah
Let loose, honey, all right
[Guitar Solo]
[Pre-Chorus]
Oh, I'm burning through the sky, yeah
Two hundred degrees, that's why they call me Mister Fahrenheit (Hey)
Travelling at the speed of light
I wanna make a supersonic man outta you (Hey, hey)
[Chorus]
(Don't stop me now)
I'm having such a good time
I'm having a ball
(Don't stop me now)
If you wanna have a good time
Just give me a call (Ooh, alright)
(Don't stop me now)
'Cause I'm having a good time (Hey, hey)
(Don't stop me now)
Yes, I'm having a good time
I don't wanna stop at all
[Outro]
Ah, da, da, da, da
Da, da, ah, ah
Ah, da, da, ah, ah, ah
Ah, da, da
Ah, da, da, ah, ah
Ooh, ooh-ooh, ooh-ooh
'''
)
#play sound
from IPython.display import Audio
play_audio('/content/drive/MyDrive/songs/3.mp3')
print("Please wait while the audio file loads and then press play for the audio to play!")
print("Lyrics and Song Generated")
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
print(
)
#singsong
print("You may sing along with the audio and lyrics or sing the song yourself after playing the audio, If your not interested, you may please skip to the next code block without inputting anything")
print("Please type any key to begin the sing along/sing alone!")
print("If you are interested and you input anything, it's pretty self-explanatory from there!.")
if input(""):
"""
To write this piece of code I took inspiration/code from a lot of places.
It was late night, so I'm not sure how much I created or just copied o.O
Here are some of the possible references:
https://blog.addpipe.com/recording-audio-in-the-browser-using-pure-html5-and-minimal-javascript/
https://stackoverflow.com/a/18650249
https://hacks.mozilla.org/2014/06/easy-audio-capture-with-the-mediarecorder-api/
https://air.ghost.io/recording-to-an-audio-file-using-html5-and-js/
https://stackoverflow.com/a/49019356
"""
from IPython.display import HTML, Audio
from google.colab.output import eval_js
from base64 import b64decode
import numpy as np
from scipy.io.wavfile import read as wav_read
import io
import ffmpeg
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 the recording... pls wait!"
}
}
// 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 get_audio():
display(HTML(AUDIO_HTML))
data = eval_js("data")
binary = b64decode(data.split(',')[1])
process = (ffmpeg
.input('pipe:0')
.output('pipe:1', format='wav')
.run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)
)
output, err = process.communicate(input=binary)
riff_chunk_size = len(output) - 8
# Break up the chunk size into four bytes, held in b.
q = riff_chunk_size
b = []
for i in range(4):
q, r = divmod(q, 256)
b.append(r)
# Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.
riff = output[:4] + bytes(b) + output[8:]
sr, audio = wav_read(io.BytesIO(riff))
return audio, sr
audio, sr = get_audio()
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(audio)
plt.show()
print("Done! You may play your recording or go to the next code block.")
print("Do you want lyrics and audio to another song. Type Yes to continue")
if input(""):
print("Do you want the lyrics and audio of Hey Jude by The Beatles")
print("Press any key if you want the lyrics and audio for Hey Jude by The Beatles")
if input(""):
print(
'''
[Verse 1: Paul McCartney]
Hey Jude, don't make it bad
Take a sad song and make it better
Remember to let her into your heart
Then you can start to make it better
[Verse 2: Paul McCartney, John Lennon, George Harrison]
Hey Jude, don't be afraid
You were made to go out and get her
The minute you let her under your skin
Then you begin to make it better
[Chorus: Paul McCartney, John Lennon, George Harrison]
And anytime you feel the pain, hey Jude, refrain
Don't carry the world upon your shoulders
For well you know that it's a fool who plays it cool
By making his world a little colder
Na na na na na na na na na na
[Verse 3: Paul McCartney]
Hey Jude, don't let me down
You have found her, now go and get her
(Let it out and let it in)
Remember (Hey Jude) to let her into your heart
Then you can start to make it better
[Chorus: Paul McCartney, John Lennon, George Harrison]
So let it out and let it in, hey Jude, begin
You're waiting for someone to perform with
And don't you know that it's just you, hey Jude, you'll do
The movement you need is on your shoulder
Na na na na na na na na na yeah
[Verse 4: Paul McCartney & John Lennon]
Hey Jude, don't make it bad
Take a sad song and make it better
Remember to let her under your skin
Then you'll begin to make it
Better better better better better better, oh
[Outro: Paul McCartney & Lennon/Harrison/Starr]
Yeah yeah yeah yeah yeah yeah yeah
Naa na na na na na na, na na na na, hey Jude
Naa na na na na na na, na na na na, hey Jude
Naa na na na na na na, na na na na, hey Jude
Naa na na na na na na, na na na na, hey Jude
(Jude Judy Judy Judy Judy Judy ow wow)
Naa na na na na na na (Na na na), na na na na, hey Jude
(Jude Jude Jude Jude Jude)
Naa na na na na na na (Yeah yeah yeah), na na na na, hey Jude
(You know you can make, Jude Jude, You're not gonna break it)
Naa na (Don't make it bad Jude) na na na na na (Take a sad song and make it better), na na na na, hey Jude
Hey Jude, hey Jude wow
Naa na na na na na na, na na na na, hey Jude
Naa na na na na na na, na na na na, hey Jude
Jude Jude Jude Jude Jude Jude