使用NumPy数组在pygame中播放MoviePy音频

2024-10-03 23:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pygame播放来自电影AudioFileClip的音频。 当我试图将NumPy数组转换为pygame可识别的对象时,我遇到了麻烦。根据docs,我可以使用pygame.sndarray.make_sound(NumPyArray)函数进行转换。我的代码:

import pygame
from moviepy.editor import *

sound = AudioFileClip("video.mp4") #sound from a video
newSound = sound.subclip("00:00:13","00:00:15.0") #clip of 13 to 15 sec.
soundArray = newSound.to_soundarray() #convert to NumPy array

pygame.init() #initialize Pygame
pygameSound = pygame.sndarray.make_sound(soundArray) #error here
pygameSound.play()

在执行时,倒数第二行的函数调用newsound = pygame.sndarray.make_sound(newsound)会传递以下错误:

^{pr2}$

为什么在这里出现ValueError?我怎样才能纠正这个问题?在


编辑:用pygame.mixer.Sound构造pygame声音对象

我还尝试更改最后一段代码来实现pygame.mixer.Sound()。根据相关的docs,函数应该是在pygame中从NumPy数组创建声音的另一种方法。然而,当我尝试这个的时候,我也遇到了一些问题。将上述代码的最后一节替换为以下内容:

^{3}$

代码执行时没有错误,但是没有声音被播放。这与我验证原始video.mp4文件中的13秒和15秒时间戳之间存在音频这一事实形成了对比。在


Tags: to对象函数代码numpy声音docsmake