lukasmaximus89
Published © GPL3+

Play WAV Files on Your M5Stack

There are bound to be times when you need to add music or SFX to your M5Stack projects. Here's how to do so with MicroPython.

IntermediateFull instructions provided1 hour8,062
Play WAV Files on Your M5Stack

Things used in this project

Hardware components

ESP32 Basic Core IoT Development Kit
M5Stack ESP32 Basic Core IoT Development Kit
×1

Software apps and online services

MicroPython
MicroPython

Story

Read more

Code

wavplayer script

MicroPython
upload to your m5stack using mu or thonny
from machine import I2S, SDCard, Pin
from m5stack import *
import os, uos
from wav import wave

#mount the sd card
sd = SDCard(slot = 2, sck = Pin(23), miso = Pin(33), mosi = Pin(19), freq = 10000000)

#initialize the I2S device
i2s = I2S(  mode = I2S.MODE_MASTER | I2S.MODE_TX | I2S.MODE_DAC_BUILT_IN,
            rate = 16000,
            bits = 16,
            channel_format = I2S.CHANNEL_ONLY_LEFT,
            data_format = I2S.FORMAT_I2S_MSB)

#create a function to play the wav
def wav_player(fname):
    wav = wave.open(fname)
    i2s.set_dac_mode(I2S.DAC_RIGHT_EN)
    i2s.sample_rate(wav.getframerate())
    i2s.bits(wav.getsampwidth() * 8)
    i2s.nchannels(wav.getnchannels())
    i2s.volume(20)

    while True:
        data = wav.readframes(1024)
        if len(data) > 0:
            i2s.write(data)
        else:
            wav.close()
            break

# Playing WAV audio file
lcd.clear()
lcd.print('working',0,0,0xffffff)

try:
    uos.mountsd(sd, '/sd')
except:
    #os.mountsd()
    pass

speaker.setVolume(2)
#kill the weird start noise glitch
i2s.stop()

#point the directory to the files you have on your sd card - works best with short low file size wavs
while True:
    if btnA.wasPressed():
        wav_player('/flash/res/yourfile.wav')
        i2s.stop()
    if btnB.wasPressed():
        wav_player('/sd/yourOtherFile.wav')
        i2s.stop()
    if btnC.wasPressed():
        wav_player('/sd/anotherfile.wav')
        i2s.stop()

Credits

lukasmaximus89

lukasmaximus89

38 projects • 32 followers
I'm Luke from Manchester, UK. I've been living in shenzhen for 6 years. I do 3D design, Basic Electronics, Casting and other cool stuff.

Comments