python-3.x - 在Python 3中播放具有开始时间和结束时间的MP3文件的最佳方式是如何

标签 python-3.x

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

我尝试过 pygame Mixer,我可以传递文件的开始时间,但我无法传递我希望音乐停止的结束时间,或者能够淡入和淡出当前片段。

我查看了 vlc 和 ffmpeg 库,但没有看到我正在寻找的功能。

我希望有人知道有一个图书馆可以完成我想要完成的任务。

最佳答案

我终于知道如何做我想做的事了!

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

我的开发环境:

Mac 操作系统 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()

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

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

关于python-3.x - 在Python 3中播放具有开始时间和结束时间的MP3文件的最佳方式是如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299042/

相关文章:

python - 如何阻止 bokeh 在 Jupyter Notebook 中打开新标签页?

python-3.x - 构建继承 Pandas DataFrame 的类

当前面没有字符串时,正则表达式匹配字符

python - 将带有回调的 Python 函数转换为可等待的 asyncio

javascript - MechanicalSoup(python 3x)可以处理网站中的javascript吗?

python-3.x - 如何修复 "OSError: [WinError 193] %1 is not a valid Win32 application"

python-3.x - 试试,除了,再试一次?

Python 2/3 subprocess.Popen和非ascii字符

ruby - 错误消息 "Xcode alone is not sufficient on Sierra"

python - Flask-SQLAlchemy 检查行是否存在