Skip to content
Advertisement

Opening wav from URL in Python

With the Python script shown below I try to play a wav file from the internet but I’m getting the error message OSError: [Errno 22] Invalid argument: 'https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav'.

How can I play a wav file from the internet?

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

Advertisement

Answer

You can also get the content of website, store it in a variable, and play it. There is no need to store it on the disk for a short file like this. Here is an example of how to do this:

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

Advertisement