python实现音频可视化,有粒子特效
时间: 2023-05-25 17:04:39 浏览: 212
用python实现音乐可视化
以下是一个简单的Python代码,实现音频可视化和粒子特效:
```python
import numpy as np
import pyaudio
import time
import math
import pygame
import random
# 配置参数
CHUNK = 2048
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
# 初始化Pygame
pygame.init()
W, H = 1024, 768
win = pygame.display.set_mode((W,H))
# 初始化粒子系统
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.vx = random.randrange(-30, 30)
self.vy = random.randrange(-30, 30)
self.color = (random.randrange(50, 255), random.randrange(50, 255), random.randrange(50, 255))
def move(self):
self.x += self.vx
self.y += self.vy
if self.x >= W or self.x < 0:
self.vx = -self.vx
if self.y >= H or self.y < 0:
self.vy = -self.vy
def draw(self):
pygame.draw.circle(win, self.color, [int(self.x), int(self.y)], 2)
particles = []
for i in range(500):
particles.append(Particle(W//2, H//2))
# 初始化音频流
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
# 循环读取音频流
while True:
data = stream.read(CHUNK)
array = np.frombuffer(data, dtype=np.int16)
# 计算频域数据,并归一化
freq_domain = np.fft.fft(array) / CHUNK
freq_domain = np.abs(freq_domain[:CHUNK//2])
# 清除图像
win.fill((0,0,0))
# 绘制频域数据
bar_x = 0
bar_w = W / (CHUNK//2)
for i in range(CHUNK//2):
bar_h = math.log(freq_domain[i] + 1) * 10
pygame.draw.rect(win, (255,255,255), (bar_x, H - bar_h, bar_w, bar_h))
bar_x += bar_w
# 更新并绘制粒子系统
for p in particles:
p.move()
p.draw()
# 刷新Pygame窗口
pygame.display.update()
# 处理Pygame事件
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
quit()
# 等待一段时间
time.sleep(0.01)
```
这个程序使用Pygame显示,Pyaudio读取音频流,numpy计算频域数据。在程序运行时,它会读取音频流并计算频域数据,然后在窗口中绘制频域条形图和粒子系统。由于该程序是循环运行的,所以只要有音频流输入,它就会实时更新可视化效果。
阅读全文