【问题标题】:pyaudio simple audioplayer with "start at" functionality具有“开始于”功能的 pyaudio 简单音频播放器
【发布时间】:2021-03-14 03:16:27
【问题描述】:

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

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 允许我从文件中实时读取原始数据,我需要这个功能。 你有什么建议吗?

【问题讨论】:

    标签: python pyaudio


    【解决方案1】:

    您只需计算音频中要移动的字节数。

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      相关资源
      最近更新 更多