用python写一个可以随话筒采集音量变化来跳动的彩虹条
时间: 2023-08-04 07:34:27 浏览: 103
测试程序_树莓派python采集485设备数据_
5星 · 资源好评率100%
好的,以下是一个简单的Python代码示例,可以实现随着话筒音量的变化而跳动的彩虹条。这个代码使用了PyAudio和Pygame库来采集音频数据和绘制彩虹条。
```python
import pyaudio
import numpy as np
import pygame
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
WINDOW_SIZE = (800, 600)
WINDOW_TITLE = 'Rainbow Bar'
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption(WINDOW_TITLE)
# 定义颜色常量
RED = (255, 0, 0)
ORANGE = (255, 165, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
INDIGO = (75, 0, 130)
VIOLET = (238, 130, 238)
# 设置彩虹颜色序列
RAINBOW_COLORS = [RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET]
# 初始化PyAudio
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
# 主循环
while True:
# 处理Pygame事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 关闭PyAudio和Pygame
stream.stop_stream()
stream.close()
p.terminate()
pygame.quit()
quit()
# 读取音频数据
data = stream.read(1024, exception_on_overflow=False)
data = np.frombuffer(data, dtype=np.int16)
# 计算音量平均值
volume = np.abs(data).mean()
# 计算当前彩虹条宽度
bar_width = int(volume / 100 * WINDOW_SIZE[0])
# 绘制彩虹条
for i in range(len(RAINBOW_COLORS)):
color = RAINBOW_COLORS[i]
x = i * int(WINDOW_SIZE[0] / len(RAINBOW_COLORS))
y = 0
width = int(WINDOW_SIZE[0] / len(RAINBOW_COLORS))
height = WINDOW_SIZE[1]
if x <= bar_width:
pygame.draw.rect(screen, color, (x, y, width, height))
# 刷新屏幕
pygame.display.update()
```
这个代码会打开一个窗口,里面会显示一个彩虹条。随着话筒音量的变化,彩虹条的宽度也会变化。彩虹条的颜色序列可以在代码中自定义。
阅读全文