我想要:
Download audio files from Youtube
我已经使用 pytube 完成了此操作,但是即使我将only_audio设置为True,它的格式仍是 mp4 。
then turn the audio files to numpy arrays
有一些适用于mp3的库,例如pydub,但不适用于mp4。当我尝试 moviepy 时,它失败了,因为没有视频,因此没有帧率。我不想下载视频,因为它会花费更长的时间。
请注意,我需要音频而不是视频。
怎么能:
download audio from youtube, and turn it into numpy arrays?
感谢您的帮助:)
编辑
多亏了这些评论,我设法使用ffmpeg将mp4转换为mp3
但是,当我尝试使用this question中的代码将其转换为numpy数组时,如下所示:
def read(f, normalized=False):
"""MP3 to numpy array"""
a = pydub.AudioSegment.from_mp3(f)
y = np.array(a.get_array_of_samples())
if a.channels == 2:
y = y.reshape((-1, 2))
if normalized:
return a.frame_rate, np.float32(y) / 2**15
else:
return a.frame_rate, y
它引发了这个错误:
Traceback (most recent call last):
File "C:\Users\myname\Google Drive\Python\Projects\Music\Downloads\Music Read.py", line 63, in <module>
print(read(x,True))
......
File "C:\Users\myname\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 1017, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
这很奇怪,因为如下所示,该路径应该可以正常工作
for f in os.listdir(path):
if (f.endswith(".mp3")):
print(f)
x = 'C:/Users/myname/Google Drive/Python/Projects/Music/Downloads/{}'.format(f)
print(os.path.exists(x))
print(open(x))
print(read(x,True))
输出:
test-Copy.mp3
True
c:/users/myname/google drive/python/projects/music/downloads/test-copy.mp3
<_io.TextIOWrapper name='c:/users/myname/google drive/python/projects/music/downloads/test-copy.mp3' mode='r' encoding='cp1252'>
另外,当我输入一个实际上不存在的文件路径时,它会输出另一个错误:
......
File "C:\Users\myname\AppData\Local\Programs\Python\Python36\lib\site-packages\pydub\utils.py", line 57, in _fd_or_path_or_tempfile
fd = open(fd, mode=mode)
FileNotFoundError: [Errno 2] No such file or directory: 'c:/users/myname/google drive/python/projects/music/downloads/hi'
How can use the code from this question to turn the mp3 into numpy arrays, if I can't, how else?
顺便说一句我正在使用python 3.6在Win10上运行
我真的希望我已经足够清楚,再次感谢您的任何建议:)
最佳答案
回答我自己的问题很奇怪,但是:
我通过使用以下代码解决了pydub问题:
def decode (fname):
# If you are on Windows use full path to ffmpeg.exe
cmd = ["C:/Users/allen/Google Drive/Python/Tools/ffmpeg-20190604-d3f236b-win64-static/bin/ffmpeg.exe", "-i", fname, "-f", "wav", "-"]
# If you are on W add argument creationflags=0x8000000 to prevent another console window jumping out
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
data = p.communicate()[0]
return np.fromstring(data[data.find(data)+4:], np.int16)
关于python - 如何将只有音频的mp4转换为numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441582/