有没有办法让pyaudio在按住按钮时录制mp3并停止录制并将mp3导出到释放按钮时的日期和时间?
我有Python 3。
我使用的按钮是 Raspberry Pi 上的物理按钮。
首先你需要安装软件包:
pip 安装 pyaudio pydub RPi.GPIO
安装 FFMPEG 包
sudo apt-get install ffmpeg
示例源代码:
import pyaudio
import wave
import time
import RPi.GPIO as GPIO
from pydub import AudioSegment
from io import BytesIO
from datetime import datetime
# Configuration
BUTTON_PIN = 17 # GPIO pin number for the button
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 0 # Not used directly in this case
# Initialize PyAudio
audio = pyaudio.PyAudio()
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def record_audio(filename):
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True, frames_per_buffer=CHUNK)
print("Recording started")
frames = []
while GPIO.input(BUTTON_PIN) == GPIO.LOW:
data = stream.read(CHUNK)
frames.append(data)
print("Recording stopped")
stream.stop_stream()
stream.close()
# Save to WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
def convert_wav_to_mp3(wav_filename, mp3_filename):
# Convert WAV to MP3 using pydub
sound = AudioSegment.from_wav(wav_filename)
sound.export(mp3_filename, format="mp3")
def main():
try:
while True:
if GPIO.input(BUTTON_PIN) == GPIO.LOW:
# Button pressed: Record audio
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
wav_filename = f"/home/pi/recordings/{timestamp}.wav"
mp3_filename = f"/home/pi/recordings/{timestamp}.mp3"
record_audio(wav_filename)
convert_wav_to_mp3(wav_filename, mp3_filename)
print(f"Audio saved to {mp3_filename}")
# Remove WAV file if desired
# os.remove(wav_filename)
# Wait a bit to avoid multiple recordings from a single press
time.sleep(1)
else:
time.sleep(0.1) # Polling delay
except KeyboardInterrupt:
print("Exiting...")
finally:
GPIO.cleanup()
audio.terminate()
if __name__ == "__main__":
main()