
本文介绍如何使用PyAudio库实现按下按钮开始播放声音,松开按钮停止声音的实时音频控制。通过修改原始代码中的循环结构和停止音频流的方式,实现对声音播放的精确控制,避免了预先定义音频时长的限制,并提供了代码示例和注意事项,帮助开发者更好地理解和应用该技术。
原始代码中存在一个关键问题:音频流的播放被限制在一个内部的while循环中,并且循环只执行一次。这导致声音只能播放很短的时间。要实现按下按钮开始播放声音,松开按钮停止声音的效果,需要对代码结构进行调整。
核心思路:
修改后的代码:
import time
from rtmidi.midiutil import open_midiinput
import numpy as np
import pyaudio
p = pyaudio.PyAudio()
# play = True # Removed this line
volume = 0.5 # range [0.0, 1.0]
fs = 44100 # sampling rate, Hz, must be integer
# duration = 5.0 # in seconds, may be float # Removed duration
fA = 440.0 # sine frequency, Hz, may be float
fB = 493.88
fC = 523.25
fD = 587.33
frekvence = 440
frekvence_seznam = {
(144, 32): fA,
(144, 33): fB,
(144, 34): fC,
(144, 35): fD,
}
port = 0
midiin, port_name = open_midiinput(port)
stream = None # Initialize stream outside the loop
try:
while True:
msg = midiin.get_message()
if msg:
message = msg
klic = message[0]
lepsi_klic = tuple(klic[:2])
print(message[0])
if lepsi_klic in frekvence_seznam:
print("je to tam")
frekvence = frekvence_seznam[lepsi_klic]
period = 2 * np.pi
# Removed duration from np.arange
x = period * np.arange(fs * 0.1) * frekvence / fs # Use a small chunk size
sinus = np.sin(x)
square = np.sign(sinus)
triangle = 2/np.pi * np.arcsin(np.sin(x))
saw = abs((x % period) - 1)
curvy_triangle = (abs((x % period) - 1)) ** 2
samples = (triangle).astype(np.float32)
# for paFloat32 sample values must be in range [-1.0, 1.0]
if stream is None or not stream.is_active(): # Check if stream is active
stream = p.open(format=pyaudio.paFloat32,
channels=1,
rate=fs,
output=True)
vysledek = volume * samples
# spusteni zvuku
stream.write(vysledek) #Removed while Loop and just write one chunk
elif lepsi_klic == (128, 32) or lepsi_klic == (128, 33) or lepsi_klic == (128, 34) or lepsi_klic == (128, 35): # Key released
print("Key Released")
if stream is not None and stream.is_active():
stream.stop_stream()
elif lepsi_klic == (144, 81):
break # Exit the main loop
finally:
if stream is not None and stream.is_active():
stream.stop_stream()
if stream is not None:
stream.close()
p.terminate()
print("Program terminated.")代码解释:
注意事项:
总结:
通过修改原始代码的循环结构和音频流控制方式,可以实现按下按钮开始播放声音,松开按钮停止声音的实时音频控制。这种方法避免了预先定义音频时长的限制,提供了更大的灵活性。在实际应用中,可以根据需要调整代码,实现更复杂的音频效果。
以上就是实时音频控制:基于PyAudio的无限时长声音播放与停止的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号