如何在Python 3中以开始时间和结束时间播放MP3文件的最佳方法

时间:2019-07-31 21:24:25

标签: python-3.x

我正在一个项目中,要求从播放列表中的MP3文件中播放声音片段。这些文件是完整的歌曲。

我尝试了pygame混音器,可以传递文件的开始时间,但是不能传递结束时间,因为我希望音乐停止播放,也不能淡入和淡出当前片段。

我看过vlc和ffmpeg库,但看不到我要的功能。

我希望有人会意识到那里的图书馆可能能够做我想完成的事情。

1 个答案:

答案 0 :(得分:1)

我终于弄清楚了该怎么做!

本着帮助他人的精神,我发布了自己的问题的答案。

我的开发环境:

Mac OS Mojave 10.14.6
Python 3.7.4
PyAudio 0.2.11
PyDub 0.23.1

这是最基本的形式:

import pyaudio
from pydub import AudioSegment

# Assign a mp3 source file to the PyDub Audiosegment
mp3 = AudioSegment.from_mp3("path_to_your_mp3_file")

# Specify starting and ending offsets from the beginning of the stream
# then apply a fadein and fadeout.  All values are  in millisecond (seconds * 1000).

mp3 = mp3[int(43000):int(58000)].fade_in(2000).fade_out(2000)

# In the above example the music will start 43 seconds into the track with a 2 second
# fade-in, and only play for 15 seconds with a 2 second fade-out.  If you don't need
# these features, just comment out the line and the full mp3 will play.

# Assign the PyAudio player
player = pyaudio.PyAudio()

# Create the stream from the chosen mp3 file
stream = player.open(format = player.get_format_from_width(mp3.sample_width),
        channels = mp3.channels,
        rate = mp3.frame_rate,
        output = True)

data = mp3.raw_data

while data:
    stream.write(data)
    data=0

stream.close()
player.terminate()

上面的示例中没有,但是有一种方法可以处理流并增加/减少/静音音乐的音量。

可以做的另一件事是设置一个线程来暂停流的处理(写入),这将模仿播放器中的暂停按钮。