通过ESP32播放音乐

问题描述 投票:0回答:1

我在使用 ESP32 和 Micropython 播放音乐时遇到问题

我有一个 MicroSD 模块、一个有 2 个引脚 (+-) 的迷你扬声器和一个 SDCard 以及下面的代码,但我不知道问题是什么! 是不是代码有问题?请帮忙!!

我已经尝试过这段代码:

from machine import Pin, I2S, SPI
import sdcard
import os

SAMPLE_RATE = 44100
BLOCK_SIZE = 512

spi = SPI(1, baudrate=10000000, polarity=0, phase=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
sd = sdcard.SDCard(spi, Pin(5))

vfs = os.VfsFat(sd)
os.mount(vfs, '/sd')

file_path = '/sd/test.mp3'
with open(file_path, 'rb') as f:
    data = f.read()

i2s = I2S(0, sck=Pin(22), ws=Pin(21), sd=Pin(4), standard=I2S.PHILIPS, mode=I2S.MASTER_TX, dataformat=I2S.B32, samplerate=SAMPLE_RATE, dmacount=8, dmalen=BLOCK_SIZE)

while True:
    i2s.write(data)

错误是这样的:

Traceback (most recent call last):
File "<stdin>", line 20, in <module>
MemoryError: memory allocation failed, allocating 82176 bytes

如果我的代码错误,请告诉我真实的类型。

python esp32 sd-card micropython speaker
1个回答
0
投票

我尝试了这段代码,输出没有错误,但扬声器没有发出音乐

import machine
from machine import Pin
import sdcard
import os

# Initialize the SPI interface
spi = machine.SPI(1, baudrate=10000000, polarity=0, phase=0, 
sck=machine.Pin(18), mosi=machine.Pin(23), miso=machine.Pin(19))

# Initialize the SD card
sd = sdcard.SDCard(spi, machine.Pin(5))
os.mount(sd, '/sd')

# Open the MP3 file
file_path = '/sd/test.mp3'
file = open(file_path, 'rb')

# Configure the audio output
audio_pin = machine.Pin(25)
audio = machine.PWM(audio_pin)

# Play the song
while True:
    data = file.read(512)
    if len(data) == 0:
        break
    audio.duty_u16(32768)  # Set the duty cycle to 50% (32768 out of 65535)
    for sample in data:
        audio.duty_u16(sample << 5)  # Scale the sample to a 16-bit value 
(shifted left by 5 bits)
        machine.freq(80000000)  # Set the frequency to 80 MHz

# Close the file
file.close()

# Unmount the SD card
os.umount('/sd')

又怎么了??????

© www.soinside.com 2019 - 2024. All rights reserved.