具有 "start at" 功能的 pyaudio 简单音频播放器

pyaudio simple audioplayer with "start at" functionality

我正在 python 使用 pyaudio 库编写一个简单的播放器,具有一些基本功能,例如开始播放、暂停和开始位置。 我开始研究文档的第一个示例:

import pyaudio
import wave
import sys

CHUNK = 1024

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

# instantiate PyAudio (1)
p = pyaudio.PyAudio()

# open stream (2)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

# read data
data = wf.readframes(CHUNK)

# play stream (3)
while len(data) > 0:
    stream.write(data)
    data = wf.readframes(CHUNK)

# stop stream (4)
stream.stop_stream()
stream.close()

# close PyAudio (5)
p.terminate()

它工作得很好,但我真的不知道在哪里添加帧偏移以在特定帧开始播放。 我看到有不同的库可用,但 PyAudio 允许我实时从文件中读取原始数据,我需要这个功能。 你有什么建议吗?

您只需计算要在音频中移动多少字节。

nbytes = wf.getsampwidth()  # Gives the number of bytes per sample for 1 channel
nchannels = wf.getnchannels()  # Number of channels
sample_rate = wf.getframerate()  # Number of samples per second  44100 is 44100 samples per second

nbytes_per_sample_per_channel = nbytes * nchannels
nbytes_per_second = nbytes_per_sample_per_channel * sample_rate

skip_seconds = 5  # Skip 5 seconds

wf.readframes(int(skip_seconds * nbytes_per_second))  # Read data that you want to skip

读取偏移量后开始播放文件

# read data
data = wf.readframes(CHUNK)

# play stream (3)
while len(data) > 0:
    stream.write(data)
    data = wf.readframes(CHUNK)

# stop stream (4)
stream.stop_stream()
stream.close()

# close PyAudio (5)
p.terminate()