How to save a block of code as a runnable file
A script is just a plain text file. There is nothing special about it - the code you copy from this guide goes into a file, you give it a name ending in .py, and Python can then run it.
wav_to_i2s_header.pyOpen a terminal and type:
nano wav_to_i2s_header.py This opens a blank file in the terminal editor, ready to paste into.
Open your text editor and create a new file.
Copy this and paste it into the file you just opened.
import sys, wave, struct
input_file = sys.argv[1] # e.g. /tmp/clip_i2s.wav
output_file = sys.argv[2] # e.g. clip.h
# wave module reads and strips the WAV header automatically -
# readframes() returns raw PCM samples only
with wave.open(input_file, 'rb') as f:
raw = f.readframes(f.getnframes())
# unpack as signed 16-bit little-endian integers (pcm_s16le)
samples = struct.unpack('<' + str(len(raw)//2) + 'h', raw)
lines = [
'#pragma once',
'#include <pgmspace.h>',
'const int16_t audio_data[] PROGMEM = {',
]
chunks = [str(s) for s in samples]
for i in range(0, len(chunks), 16):
lines.append(' ' + ', '.join(chunks[i:i+16]) + ',')
lines.append('};')
lines.append('const size_t audio_len = sizeof(audio_data);')
with open(output_file, 'w') as f:
f.write('\n'.join(lines) + '\n')
print('Done: ' + str(len(samples)) + ' samples -> ' + output_file) nano: press Ctrl+O, then Enter to confirm the filename, then Ctrl+X to exit.
Text editor: save as wav_to_i2s_header.py. Make sure it saves as plain text - not a Word document or rich text file. Your home folder (/home/yourname/) or a project folder works well.
python3 wav_to_i2s_header.py /tmp/clip_i2s.wav clip.h Place clip.h in your sketch folder - the same directory as your .ino file.