-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaudio.py
More file actions
168 lines (140 loc) · 4.98 KB
/
Copy pathaudio.py
File metadata and controls
168 lines (140 loc) · 4.98 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
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
import logging
from typing import List, Tuple, Callable
try:
import alsaaudio
alsaaudio_available = True
except ImportError:
import pyaudio
alsaaudio_available = False
if alsaaudio_available:
import pyaudio
pyaudio_alsaaudio_foramt_mapping = {
pyaudio.paInt16: alsaaudio.PCM_FORMAT_S16_LE,
pyaudio.paInt24: alsaaudio.PCM_FORMAT_S24_LE,
pyaudio.paInt32: alsaaudio.PCM_FORMAT_S32_LE,
}
logger = logging.getLogger()
class AudioPlayer:
def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 16000):
self.format = format
self.channels = channels
self.rate = rate
if alsaaudio_available:
self.stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, channels=channels,
rate=rate, format=pyaudio_alsaaudio_foramt_mapping[format],
periodsize=128, device='default')
else:
self.pa = pyaudio.PyAudio()
self.stream = self.pa.open(format=format,
channels=channels,
rate=rate,
output=True,
start=True)
def __del__(self):
self.stream.close()
if not alsaaudio_available:
self.pa.terminate()
def play(self, audio_data: bytes) -> None:
offset = 0
chunk = 128 * self.channels
while True:
data = audio_data[offset:offset + chunk]
offset += chunk
if not data:
break
self.stream.write(data)
class AudioRecorder:
def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 8000, chunk: int = 1024):
# 设置音频参数
self.format = format
self.channels = channels
self.rate = rate
self.chunk = chunk
if alsaaudio_available:
pass
else:
self.pa = pyaudio.PyAudio()
self.is_recording = False
def __del__(self):
if not alsaaudio_available:
self.pa.terminate()
def start_recording(self, callback: Callable = None):
if self.is_recording:
return
logger.info("录音开始...")
self.is_recording = True
try:
frames = []
# 打开音频流
if alsaaudio_available:
stream = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK,
channels=self.channels, rate=self.rate,
format=pyaudio_alsaaudio_foramt_mapping[self.format],
periodsize=128, periods=8, device='default')
else:
stream = self.pa.open(format=self.format,
channels=self.channels,
rate=self.rate,
input=True,
start=True)
# 循环读取音频流
while self.is_recording:
if alsaaudio_available:
l, data = stream.read()
if l > 0:
frames.append(data)
else:
data = stream.read(self.chunk)
frames.append(data)
# 回调音频数据后处理函数
if callback:
callback(b''.join(frames))
# 停止和关闭流
stream.close()
except Exception as e:
logger.error(f"录音异常: {e}")
def stop_recording(self):
if self.is_recording:
self.is_recording = False
logger.info("录音结束...")
class AudioVolumeControl:
def __init__(self):
self.volume = 100
if alsaaudio_available:
self.mixer = alsaaudio.Mixer("Speaker", 0)
self.set(self.volume)
def get(self):
if alsaaudio_available:
vol = self.mixer.getvolume()
vol = int(vol[0])
else:
vol = self.volume
return vol
def set(self, volume: int):
self.volume = volume
if alsaaudio_available:
self.mixer.setvolume(volume)
def up(self, step: int = 10):
vol = self.get() + step
if vol > 100:
vol = 100
self.set(vol)
return vol
def down(self, step: int = 10):
vol = self.get() - step
if vol < 0:
vol = 0
self.set(vol)
return vol
if __name__ == '__main__':
import os
import sys
import time
from threading import Thread
audio_player = AudioPlayer(channels=1, rate=16000)
audio_recorder = AudioRecorder(channels=1, rate=16000)
def play_audio(audio_data: bytes):
audio_player.play(audio_data)
Thread(target=audio_recorder.start_recording, args=(play_audio,)).start()
time.sleep(10)
audio_recorder.stop_recording()