在 Python 中从 URL 打开 wav

Opening wav from URL in Python

使用下面显示的 Python 脚本,我尝试从互联网播放 wav 文件,但收到错误消息 OSError: [Errno 22] Invalid argument: 'https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav'

如何播放来自互联网的 wav 文件?

import pyaudio
import wave

chunk = 1024

f = wave.open("https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav","rb")
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
                channels = f.getnchannels(),
                rate = f.getframerate(),
                output = True)
data = f.readframes(chunk)

while data:
    stream.write(data)
    data = f.readframes(chunk)

stream.stop_stream()
stream.close()

p.terminate()

我正在演示@larsks 的建议。

import requests

with open(audio_file, 'wb') as a:
    resp = requests.get("https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav")
    if resp.status_code == 200:
        a.write(resp.content)
        print('downloaded')
    else:
        print(resp.reason)
        exit(1)

f = wave.open(audio_file, "rb")


# the remaining lines are the same

我还建议另一个很棒的 python 库 python-mpv which is based on mpv,这个库可以处理更多的编解码器和在线流媒体播放。

您还可以获取网站内容,将其存储在一个变量中,然后播放。这么短的文件没必要存到磁盘上。以下是如何执行此操作的示例:

import logging

import requests
import simpleaudio

sample_rate = 8000
num_channels = 2
bytes_per_sample = 2

total = sample_rate * num_channels * bytes_per_sample

logging.basicConfig(level=logging.INFO)

audio_url = "https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav"

logging.info(f"Downloading audio file from: {audio_url}")
content = requests.get(audio_url).content

# Just to ensure that the file does not have extra bytes
blocks = len(content) // total
content = content[:total * blocks]

wave = simpleaudio.WaveObject(audio_data=content,
                              sample_rate=sample_rate,
                              num_channels=num_channels,
                              bytes_per_sample=bytes_per_sample)
control = wave.play()
control.wait_done()