-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio.py
86 lines (65 loc) · 2.62 KB
/
audio.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
#!/usr/bin/env python3
##### HOMEMADE CODE
##### OTHERS' CODE
import numpy as np
import math
import wave
import simpleaudio as sa
class Sound(object):
def __init__(self, freq, duration):
self.frequency = freq # Our played note will be 440 Hz
self.fs = 44100 # 44100 samples per second
self.seconds = duration
# Generate array with seconds*sample_rate steps, ranging between 0 and seconds
t = np.linspace(0, self.seconds, int(math.ceil(self.seconds * self.fs)), False)
# Generate a 440 Hz sine wave
self.note = np.sin(self.frequency * t * 2 * np.pi)
# Ensure that highest value is in 16-bit range
self.audio = self.note * (2 ** 15 - 1) / np.max(np.abs(self.note))
# Convert to 16-bit data
self.audio = self.audio.astype(np.int16)
print(f"\nObject audio initiliased\n")
def play(self, event=None):
try:
if event != None:
event.wait()
# time.sleep(1)
# Start playback
self.play_obj = sa.play_buffer(self.audio, 1, 2, self.fs)
print(f"\nTONE ON\n")
if event != None:
while event.is_set():
pass
sa.stop_all()
print(f"\nTone OFF\n")
except Exception as e:
print(e)
def stop(self):
sa.stop_all()
def playEndGlobal(self, stimulus, event=None):
try:
while True:
if stimulus == 2:
self.play_obj = sa.play_buffer(self.audio, 1, 2, self.fs)
print(f"\nTONE ON\n")
break
while True:
if stimulus == 4:
print(f"\nTone OFF\n")
break
sa.stop_all()
except Exception as e:
print(e)
################################################################################################################
################################################################################################################
############################ FUNCTIONS
################################################################################################################
################################################################################################################
def saveAudioFile(path_audios, name_file, recorded, channels=1, fs=44100):
audio_file_name = f"{path_audios}/{name_file}.wav"
wf = wave.open(audio_file_name, "wb")
wf.setnchannels(channels)
wf.setsampwidth(2)
wf.setframerate(fs)
wf.writeframes(b"".join(recorded))
wf.close()