Search code examples
audioluaesp8266nodemcu

NodeMCU playing .wav or .mp3 files


I am not sure which road to go down in order to get a NodeMCU to play audio. I would like to use one to two second wav files and drive a tiny speaker. The goal is to hear a human voice, nothing super high fidelity. Additionally I don't want to use an audio shield or sd card. My files will be small enough to run everything right from the chip. There is no need to record samples, just playback. What should I use and are there any examples out there? It seems the sigma-delta module is a good place to start.


Solution

  • Once https://github.com/nodemcu/nodemcu-firmware/pull/1255 has landed on dev branch you can do the following as documented:

    -- ****************************************************************************
    -- Play file with pcm module.
    --
    -- Upload jump_8k.u8 to spiffs before running this script.
    --
    -- ****************************************************************************
    
    
    function cb_drained(d)
      print("drained "..node.heap())
    
      file.seek("set", 0)
      -- uncomment the following line for continuous playback
      --d:play(pcm.RATE_8K)
    end
    
    function cb_stopped(d)
      print("playback stopped")
      file.seek("set", 0)
    end
    
    function cb_paused(d)
      print("playback paused")
    end
    
    file.open("jump_8k.u8", "r")
    
    drv = pcm.new(pcm.SD, 1)
    
    -- fetch data in chunks of LUA_BUFFERSIZE (1024) from file
    drv:on("data", file.read)
    
    -- get called back when all samples were read from the file
    drv:on("drained", cb_drained)
    
    drv:on("stopped", cb_stopped)
    drv:on("paused", cb_paused)
    
    -- start playback
    drv:play(pcm.RATE_8K)
    

    Audio is expected as a mono raw unsigned 8 bit stream at sample rates between 1 k and 16 k samples per second. Regular WAV files can be converted with OSS tools like Audacity or SoX. Adjust the volume before the conversion.