-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVoiceRecorder.py
More file actions
104 lines (77 loc) · 2.58 KB
/
VoiceRecorder.py
File metadata and controls
104 lines (77 loc) · 2.58 KB
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
import pyaudio
import wave
import VoiceHAB as VH
import Settings
from sys import byteorder
from array import array
from struct import pack
def IsRecordingSilent(SoundData):
return max(SoundData) < VH.MicThreshold
def NormalizeRecording(SoundData):
Times = float(16384) / max(abs(i) for i in SoundData)
r = array('h')
for i in SoundData:
r.append(int(i * Times))
return r
def TrimRecording(SoundData):
def _trim(SoundData):
RecordingStarted = False
r = array('h')
for i in SoundData:
if not RecordingStarted and abs(i) > VH.MicThreshold:
RecordingStarted = True
r.append(i)
elif RecordingStarted:
r.append(i)
return r
SoundData = _trim(SoundData)
SoundData.reverse()
SoundData = _trim(SoundData)
SoundData.reverse()
return SoundData
def AddSilence(SoundData, Seconds):
r = array('h', [0 for i in range(int(Seconds * int(Settings.VoiceRecorderRate)))])
r.extend(SoundData)
r.extend([0 for i in range(int(Seconds * int(Settings.VoiceRecorderRate)))])
return r
def RecordSound():
p = pyaudio.PyAudio()
SoundStream = p.open(
format = pyaudio.paInt16,
channels = 1,
rate = int(Settings.VoiceRecorderRate),
input = True,
output = True,
frames_per_buffer = int(Settings.VoiceRecorderChunkSize))
CountSilent = 0
RecordingStarted = False
r = array('h')
while 1:
SoundData = array('h', SoundStream.read(int(Settings.VoiceRecorderChunkSize)))
if byteorder == 'big':
SoundData.byteswap()
r.extend(SoundData)
Silent = IsRecordingSilent(SoundData)
if Silent and RecordingStarted:
CountSilent += 1
elif not Silent and not RecordingStarted:
RecordingStarted = True
if RecordingStarted and CountSilent > 30:
break
SampleWidth = p.get_sample_size(pyaudio.paInt16)
SoundStream.stop_stream()
SoundStream.close()
p.terminate()
r = NormalizeRecording(r)
r = TrimRecording(r)
r = AddSilence(r, 0.5)
return SampleWidth, r
def RecordToFile(Path):
SampleWidth, SoundData = RecordSound()
SoundData = pack('<' + ('h' * len(SoundData)), *SoundData)
RecordedFile = wave.open(Path, 'wb')
RecordedFile.setnchannels(1)
RecordedFile.setsampwidth(SampleWidth)
RecordedFile.setframerate(int(Settings.VoiceRecorderRate))
RecordedFile.writeframes(SoundData)
RecordedFile.close()