[英]Playing audio in python at given timestamp
我试图在 python 中找到一种方法来播放给定开始和结束时间的音频文件的一部分。
例如,假设我有一个持续时间为 1 分钟的音频文件。 我想播放从 0:30 到 0:45 秒的部分。
我不想处理或拼接文件,只想播放给定的部分。
任何建议将不胜感激!
更新:
我使用 pydub 找到了一个很好的解决方案:
https://github.com/jiaaro/pydub
from pydub import AudioSegment
from pydub.playback import play
audiofile = #path to audiofile
start_ms = #start of clip in milliseconds
end_ms = #end of clip in milliseconds
sound = AudioSegment.from_file(audiofile, format="wav")
splice = sound[start_ms:end_ms]
play(splice)
第一步是让你的python播放整个音频文件......有几个库可以用于这个......看看该库是否有特定时间的api调用......你可以随时卷起袖子并在你之后自己实现将音频文件读入缓冲区或可能流式传输文件并在所选时间段结束时停止流式传输
另一种选择是利用命令行工具,比如 ffmpeg,它是音频处理的瑞士军刀……ffmpeg 有命令行输入参数来执行特定时间的启动和停止……也看看它的兄弟 ffplay
与 ffplay/ffmpeg 类似的是另一个名为 sox 的命令行音频工具
我总是在安装外部库时遇到问题,如果您在服务器上运行代码并且没有 sudo 权限,那么它会变得更加麻烦。 甚至不要让我开始安装 ffmpeg。 因此,这是一个使用 scipy 和本机 IPython 的替代解决方案,可以避免安装其他库的麻烦。
from scipy.io import wavfile # to read and write audio files
import IPython #to play them in jupyter notebook without the hassle of some other library
def PlayAudioSegment(filepath, start, end, channel='none'):
# get sample rate and audio data
sample_rate, audio_data = wavfile.read(filepath) # where filepath = 'directory/audio.wav'
#get length in minutes of audio file
print('duration: ', audio_data.shape[0] / sample_rate / 60,'min')
## splice the audio with prefered start and end times
spliced_audio = audio_data[start * sample_rate : end * sample_rate, :]
## choose left or right channel if preferred (0 or 1 for left and right, respectively; or leave as a string to keep as stereo)
spliced_audio = spliced_audio[:,channel] if type(channel)==int else spliced_audio
## playback natively with IPython; shape needs to be (nChannel,nSamples)
return IPython.display.Audio(spliced_audio.T, rate=sample_rate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.