pip install pydub
pip install ffmpeg
pip install pyaudio
完整代码如下:
import pygame,sys
import random
import numpy as np
from random import randint
import colorsys
from pydub import AudioSegment
import math
def rnd_color(): #随机颜色
h,s,l = random.random(),0.5+random.random()/2.0,0.4+random.random()/5.0
return [int(256*i) for i in colorsys.hls_to_rgb(h,l,s)]
pygame.init()
screen_width, screen_height = 800, 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("音乐可视化")
AudioSegment.converter = "ffmpeg.exe" #去官网手动下载
AudioSegment.ffmpeg = "ffmpeg.exe"
AudioSegment.ffprobe = "ffprobe.exe"
audio_path = "chengdu.mp3" # 音频文件路径
audio = AudioSegment.from_mp3(audio_path)
audio_data = np.array(audio.get_array_of_samples(), dtype=np.int16)
print(audio.frame_rate) #采样率
print(len(audio_data))
print(audio.duration_seconds) #时长
track = pygame.mixer.music.load("chengdu.mp3")
pygame.mixer.music.play() # 播放
# 等待直到播放结束
while pygame.mixer.music.get_busy():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.mixer.music.stop()
pygame.quit()
sys.exit()
screen.fill((0,0,0))
circle_color = rnd_color()
tm = pygame.mixer.music.get_pos() #当前播放的位置(时间)
tm = int(tm/1000*2*44100) #根据播放时间计算出数组下标
for i in range(44100*2):
t = int( tm+i )
radius = audio_data[t]/32767 * (screen.get_height()/2) #根据屏幕高度缩放
pygame.draw.line(screen,circle_color,
(i*screen.get_width()/44100/2,screen.get_height()/2-radius),
(i*screen.get_width()/44100/2,screen.get_height()/2))
pygame.display.flip()
效果图(随着音乐的播放而律动):