我已经编写了加载音频文件、计算频谱和动画效果的代码,但我似乎没有使用的工具来将音频与动画进行同步。
我遇到的难题是 pydub 并没有告诉我我目前正在音频中的位置(尽管我可以计时),而 matplotlib 则没有让我控制动画的进度,并且它也不能保证帧速率。
有没有一种技术或工具组合,能够解决这个特定的问题?
以下是我的代码:
我遇到的难题是 pydub 并没有告诉我我目前正在音频中的位置(尽管我可以计时),而 matplotlib 则没有让我控制动画的进度,并且它也不能保证帧速率。
有没有一种技术或工具组合,能够解决这个特定的问题?
以下是我的代码:
from pydub import AudioSegment
from pydub.playback import play
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy import signal
import numpy as np
import threading
import time
from datetime import timedelta
# Load the audio and get the raw data for transformation
sound = AudioSegment.from_mp3("A Day Without Rain - Enya - Flora's Secret.mp3")
sampling_rate = sound.frame_rate
song_length = sound.duration_seconds
left = sound.split_to_mono()[0]
x = left.get_array_of_samples()
# Fourier transform
f, t, Zxx = signal.stft(x, fs=sampling_rate, nperseg=8820, noverlap=5292)
y = np.abs(Zxx.transpose())
# Setup a separate thread to play the music
music_thread = threading.Thread(target=play, args=(sound,))
# Build the figure
fig = plt.figure(figsize=(14, 6))
plt.style.use('seaborn-bright')
ax = plt.axes(xlim=[0, 4000], ylim=[0, 3000])
line1, = ax.plot([], [])
# Matplotlib function to initialize animation
def init():
global annotation1, annotation2
line1.set_data([], [])
annotation1 = plt.annotate("Music: {}".format(""), xy=(0.2, 0.8), xycoords='figure fraction')
annotation2 = plt.annotate("Animation: {}".format(""), xy=(0.6, 0.8), xycoords='figure fraction')
return line1,
# Function for the animation
def animate(i):
global music_start, annotation1, annotation2
line1.set_data(f, y[i])
if i == 0:
music_thread.start()
music_start = time.perf_counter()
annotation1.set_text("Music: {}".format(timedelta(seconds=(time.perf_counter() - music_start))))
annotation2.set_text("Animation: {}".format(timedelta(seconds=i / t.size * song_length)))
return line1,
anim = FuncAnimation(fig, animate, init_func=init, interval=55)
plt.show()