Reputation: 43
I want to stream mp3 audio from a URL using the Raspberry Pi Pico W. This is my code:
import adafruit_requests
import wifi
import socketpool
import ssl
import board
import audiomp3
import audiobusio
import os
audio = audiobusio.I2SOut(board.GP10, board.GP11, board.GP9)
mp3_url = "http://codeskulptor-demos.commondatastorage.googleapis.com/descent/background%20music.mp3"
chunk_size = 1024
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
try:
doc = requests.get(mp3_url)
with open('sound.mp3', 'wb') as f:
for chunk in doc.iter_content(chunk_size=chunk_size):
f.write(chunk)
print("downloaded")
mp3 = audiomp3.MP3Decoder(open("sound.mp3", "rb"))
mp3.sample_rate=24000
audio.play(mp3)
while audio.playing:
pass
print("done playing")
except Exception as e:
print("error in creating mp3 or playing audio:\n", str(e))
It currently downloads the mp3 in chunks and writes it to a file. The problem is, it takes too long, because I have to wait for the entire file to be downloaded first. How can I modify this code to start playing the audio after I send the request, and start streaming it as soon as enough data is available?
Upvotes: 2
Views: 732
Reputation: 2247
@lixas is correct. You can pass a file to audiobusio, but not a stream.
https://docs.circuitpython.org/en/latest/shared-bindings/audiobusio/index.html
Upvotes: 0