|
|
import pyaudio |
|
|
import wave |
|
|
import audioop |
|
|
|
|
|
class Record: |
|
|
def __init__(self, output_file, silence_threshold=1000): |
|
|
self.output_file = output_file |
|
|
self.silence_threshold = silence_threshold |
|
|
|
|
|
|
|
|
self.format = pyaudio.paInt16 |
|
|
self.channels = 1 |
|
|
self.sample_rate = 44100 |
|
|
self.chunk = 1024 |
|
|
self.audio = pyaudio.PyAudio() |
|
|
|
|
|
def start_recording(self): |
|
|
|
|
|
stream = self.audio.open(format=self.format, |
|
|
channels=self.channels, |
|
|
rate=self.sample_rate, |
|
|
input=True, |
|
|
frames_per_buffer=self.chunk) |
|
|
|
|
|
print("开始录音...") |
|
|
|
|
|
frames = [] |
|
|
silence_counter = 0 |
|
|
|
|
|
|
|
|
while True: |
|
|
data = stream.read(self.chunk) |
|
|
frames.append(data) |
|
|
|
|
|
|
|
|
rms = audioop.rms(data, 2) |
|
|
|
|
|
if rms < self.silence_threshold: |
|
|
silence_counter += 1 |
|
|
else: |
|
|
silence_counter = 0 |
|
|
|
|
|
|
|
|
if silence_counter >= 100: |
|
|
break |
|
|
|
|
|
print("录音结束.") |
|
|
|
|
|
|
|
|
stream.stop_stream() |
|
|
stream.close() |
|
|
self.audio.terminate() |
|
|
|
|
|
|
|
|
with wave.open(self.output_file, 'wb') as wf: |
|
|
wf.setnchannels(self.channels) |
|
|
wf.setsampwidth(self.audio.get_sample_size(self.format)) |
|
|
wf.setframerate(self.sample_rate) |
|
|
wf.writeframes(b''.join(frames)) |
|
|
|
|
|
|
|
|
def test(): |
|
|
|
|
|
output_file = "recording.wav" |
|
|
silence_threshold = 500 |
|
|
|
|
|
recorder = Record(output_file, silence_threshold) |
|
|
recorder.start_recording() |
|
|
|
|
|
|