Skip to content

Commit a53d114

Browse files
committed
Added wave generation and saving.
1 parent 4141c9d commit a53d114

File tree

3 files changed

+76
-2
lines changed

3 files changed

+76
-2
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
__pycache__
1+
__pycache__
2+
output

constants.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,7 @@
1717
TEXT_QUIT = "🚪 quit ::: Closes the application"
1818
TEXT_NOT_LOADED = "🤔 I couldn't find this sound wave, did you load it? "
1919
TEXT_INVALID_SYNTAX = "🤔 I couldn't understand that. Try this command:"
20+
TEXT_GENERATE = "🎧 gen [name] [harmonics] [duration] ::: Generates a sound wave with the given name and number of harmonics, lasting [duration] ms. If no name provided, name will be generated. Harmonics number equals 10 by default. Duration equals 100 (ms) by default."
21+
TEXT_ERROR_WRITING = "❌ There was an error while saving the wave "
22+
TEXT_GENERATED = "💽 You're officially an artist. Here's your sound wave: "
23+
TEXT_PLOTTING = "📈 Plotting..."

main.py

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
import random
12
from tkinter.tix import TEXT
23
from typing import Dict, List
34
import wave
45
import numpy as np
56
import sys
67
import matplotlib.pyplot as plt
78
import os
9+
import regex as re
810
from constants import *
911

1012

@@ -200,6 +202,34 @@ def quit():
200202
sys.exit(0)
201203

202204

205+
def generate_wave(name, n, t):
206+
"""
207+
Generates a sinusoidal sound wave comprised of n harmonics, all totaling t duration.
208+
"""
209+
framerate = 44100
210+
T = np.arange(framerate * t / 1000) / framerate
211+
vals = np.zeros(len(T))
212+
while n > 0:
213+
a = random.randint(1, 10) / 10
214+
f = random.randint(10, 100)
215+
omega = 2 * np.pi * f
216+
vals += (a * np.sin(omega * T))
217+
n -= 1
218+
219+
if not os.path.exists("./output"):
220+
os.makedirs("./output")
221+
wav = wave.open("./output/" + name + ".wav", "wb")
222+
wav.setframerate(framerate)
223+
wav.setnchannels(1)
224+
wav.setsampwidth(4)
225+
226+
# Write sound
227+
wav.writeframes(vals)
228+
229+
sw = SoundWave(name, wav, vals)
230+
return sw
231+
232+
203233
# Helper global dict of all loaded soundwaves.
204234
sound_waves: Dict[str, SoundWave] = {}
205235

@@ -220,6 +250,7 @@ def main():
220250
print("✅ Done!")
221251

222252
print("\n🚀 Enter your commands below:")
253+
223254
while True:
224255

225256
cmd = input("\n> ").strip().split(" ")
@@ -254,6 +285,43 @@ def main():
254285
else:
255286
print(f"🚩 No speech detected in {sw.name}!")
256287

288+
elif func == "gen":
289+
if len(cmd) < 2:
290+
name = "wave-" + str(len(sound_waves.keys()))
291+
else:
292+
if re.search("[^a-zA-Z0-9_\\-]", cmd[1]) != None:
293+
print(
294+
f"😅 Oops! The sound wave name can only comprise of a-z, A-Z, 0-9, '_' or '-' characters. How about \"Bach-Outclassed-2022\"?")
295+
continue
296+
297+
name = cmd[1]
298+
299+
if len(cmd) < 3:
300+
n = 10
301+
else:
302+
if re.search("\D", cmd[2]) != None:
303+
print(
304+
f"😅 Oops! You specified an invalid number of harmonics: \"{cmd[2]}\" - try giving a number, like 10!")
305+
continue
306+
307+
n = int(cmd[2])
308+
309+
if len(cmd) < 4:
310+
t = 100
311+
else:
312+
if re.search("\D", cmd[3]) != None:
313+
print(
314+
f"😅 Oops! You specified an invalid wave duration: \"{cmd[2]}\" - try giving a number, like 100!")
315+
continue
316+
317+
t = int(cmd[3])
318+
319+
sw = generate_wave(name, n, t)
320+
print(TEXT_GENERATED + name)
321+
print(TEXT_PLOTTING)
322+
sound_waves[sw.name] = sw
323+
plot_waves([sw])
324+
257325
elif func == "list":
258326
if len(cmd) > 1:
259327
list_waves(sound_waves, cmd[1])
@@ -303,7 +371,7 @@ def main():
303371
if br:
304372
continue
305373

306-
print(f"📈 Plotting...")
374+
print(TEXT_PLOTTING)
307375
plot_waves(to_compare, type=plot_type)
308376

309377
elif func == "quit":
@@ -312,6 +380,7 @@ def main():
312380
else:
313381
print("\n=== Help ===\n")
314382
print(f"{TEXT_CLEAN}\n")
383+
print(f"{TEXT_GENERATE}\n")
315384
print(f"{TEXT_HELP}\n")
316385
print(f"{TEXT_LIST}\n")
317386
print(f"{TEXT_LOAD}\n")

0 commit comments

Comments
 (0)