Last active
March 6, 2024 08:46
-
-
Save nikola-j/fb19a69f6c47ff438e87c7dac5ea5dd1 to your computer and use it in GitHub Desktop.
Micropython play wav file forever on M5stack atom echo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import uasyncio as asyncio | |
from machine import I2S, Pin | |
# I2S configuration | |
device_config = { | |
'bck': 19, | |
'ws': 33, | |
'sdout': 22, | |
} | |
SAMPLES_PER_SECOND = 16000 | |
bck_pin = Pin(device_config['bck']) | |
ws_pin = Pin(device_config['ws']) | |
sdout_pin = Pin(device_config['sdout']) | |
# Initialize I2S | |
audio_out = I2S(0, sck=bck_pin, ws=ws_pin, sd=sdout_pin, mode=I2S.TX, | |
bits=16, format=I2S.STEREO, rate=SAMPLES_PER_SECOND, ibuf=10000) | |
# Coroutine to play audio | |
async def play_audio(file_path, audio_out): | |
# Open the WAV file | |
with open(file_path, 'rb') as s: | |
s.seek(44) # Skip WAV header | |
# Create a StreamWriter for non-blocking I/O | |
loop = asyncio.get_event_loop() | |
swriter = asyncio.StreamWriter(audio_out, {}) | |
# Buffer to hold audio data | |
buffer = bytearray(1024) | |
# Continuously read and play audio | |
while True: | |
num_bytes = s.readinto(buffer) | |
if num_bytes: | |
swriter.write(buffer[:num_bytes]) # Write only the bytes read | |
await swriter.drain() # Wait for data to be sent | |
else: | |
# If end of file, loop back | |
s.seek(44) | |
# Main coroutine | |
async def main(): | |
await play_audio('pink.wav', audio_out) | |
# Run the event loop | |
try: | |
asyncio.run(main()) | |
except KeyboardInterrupt: | |
print("Playback interrupted by user.") | |
finally: | |
audio_out.deinit() | |
print("Audio output deinitialized.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment