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?
JavaScript
x
22
22
1
import pyaudio
2
import wave
3
4
chunk = 1024
5
6
f = wave.open("https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav","rb")
7
p = pyaudio.PyAudio()
8
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
9
channels = f.getnchannels(),
10
rate = f.getframerate(),
11
output = True)
12
data = f.readframes(chunk)
13
14
while data:
15
stream.write(data)
16
data = f.readframes(chunk)
17
18
stream.stop_stream()
19
stream.close()
20
21
p.terminate()
22
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:
JavaScript
1
30
30
1
import logging
2
3
import requests
4
import simpleaudio
5
6
sample_rate = 8000
7
num_channels = 2
8
bytes_per_sample = 2
9
10
total = sample_rate * num_channels * bytes_per_sample
11
12
logging.basicConfig(level=logging.INFO)
13
14
audio_url = "https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav"
15
16
logging.info(f"Downloading audio file from: {audio_url}")
17
content = requests.get(audio_url).content
18
19
# Just to ensure that the file does not have extra bytes
20
blocks = len(content) // total
21
content = content[:total * blocks]
22
23
wave = simpleaudio.WaveObject(audio_data=content,
24
sample_rate=sample_rate,
25
num_channels=num_channels,
26
bytes_per_sample=bytes_per_sample)
27
control = wave.play()
28
control.wait_done()
29
30