備忘錄_20160105(定位) 修改 回首頁

程式 2023-04-18 01:24:10 1681752250 100
ESP32 S3 + MAX98357 I2S 失敗(最接近成功的一次)

ESP32 S3 + MAX98357 I2S 失敗(最接近成功的一次)

from machine import I2S
from machine import Pin

# ESP32
sck_pin = Pin(13)   # Serial clock output
ws_pin = Pin(14)    # Word clock output
sd_pin = Pin(12)    # Serial data output

led=Pin(2,Pin.OUT) #create LED object from pin2,Set Pin2 to output

audio_out = I2S(0,
                sck=sck_pin, ws=ws_pin, sd=sd_pin,
                mode=I2S.TX,
                bits=16,
                format=I2S.MONO,
                rate=8000,
                ibuf=8000)

wav = open('test.wav','rb')

# advance to first byte of Data section in WAV file
pos = wav.seek(44) 

# allocate sample arrays
#   memoryview used to reduce heap allocation in while loop
wav_samples = bytearray(2048)
wav_samples_mv = memoryview(wav_samples)

print('Starting')
# continuously read audio samples from the WAV file 
# and write them to an I2S DAC
myval=0
while True:
    try:
        num_read = wav.readinto(wav_samples_mv)
        num_written = 0
        # end of WAV file?
        if num_read == 0:
            # advance to first byte of Data section
            pos = wav.seek(44) 
        else:
            # loop until all samples are written to the I2S peripheral
            myval=(myval+1) % 2
            led.value(myval)
            while num_written < num_read:
                num_written += audio_out.write(wav_samples_mv[num_written:num_read])
    except (KeyboardInterrupt, Exception) as e:
        print('caught exception {} {}'.format(type(e).__name__, e))
        break
    
wav.close()
audio_out.deinit()
print('Done')