|
26 | 26 |
|
27 | 27 | """ |
28 | 28 |
|
| 29 | +import os |
| 30 | + |
| 31 | +import adafruit_sdcard |
29 | 32 | import adafruit_tlv320 |
30 | 33 | import audiobusio |
| 34 | +import audiocore |
31 | 35 | import board |
| 36 | +import busio |
| 37 | +import digitalio |
32 | 38 | import displayio |
33 | 39 | import framebufferio |
34 | 40 | import picodvi |
| 41 | +import storage |
35 | 42 | import supervisor |
36 | 43 | from digitalio import DigitalInOut, Direction, Pull |
37 | 44 | from neopixel import NeoPixel |
@@ -140,6 +147,35 @@ def __init__(self): |
140 | 147 |
|
141 | 148 | self._audio = audiobusio.I2SOut(board.I2S_BCLK, board.I2S_WS, board.I2S_DIN) |
142 | 149 |
|
| 150 | + self._sd_mounted = False |
| 151 | + sd_pins_in_use = False |
| 152 | + SD_CS = board.SD_CS |
| 153 | + # try to Connect to the sdcard card and mount the filesystem. |
| 154 | + try: |
| 155 | + # initialze CS pin |
| 156 | + cs = digitalio.DigitalInOut(SD_CS) |
| 157 | + except ValueError: |
| 158 | + # likely the SDCard was auto-initialized by the core |
| 159 | + sd_pins_in_use = True |
| 160 | + |
| 161 | + # if placeholder.txt file does not exist |
| 162 | + if "placeholder.txt" not in os.listdir("/sd/"): |
| 163 | + self._sd_mounted = True |
| 164 | + |
| 165 | + if not sd_pins_in_use: |
| 166 | + try: |
| 167 | + # if sd CS pin was not in use |
| 168 | + # try to initialize and mount the SDCard |
| 169 | + sdcard = adafruit_sdcard.SDCard( |
| 170 | + busio.SPI(board.SD_SCK, board.SD_MOSI, board.SD_MISO), cs |
| 171 | + ) |
| 172 | + vfs = storage.VfsFat(sdcard) |
| 173 | + storage.mount(vfs, "/sd") |
| 174 | + self._sd_mounted = True |
| 175 | + except OSError: |
| 176 | + # sdcard init or mounting failed |
| 177 | + self._sd_mounted = False |
| 178 | + |
143 | 179 | @property |
144 | 180 | def button1(self) -> bool: |
145 | 181 | """ |
@@ -175,3 +211,30 @@ def dac(self): |
175 | 211 | @property |
176 | 212 | def audio(self): |
177 | 213 | return self._audio |
| 214 | + |
| 215 | + def sd_check(self): |
| 216 | + return self._sd_mounted |
| 217 | + |
| 218 | + def play_file(self, file_name, wait_to_finish=True): |
| 219 | + """Play a wav file. |
| 220 | +
|
| 221 | + :param str file_name: The name of the wav file to play on the speaker. |
| 222 | + :param bool wait_to_finish: flag to determine if this is a blocking call |
| 223 | +
|
| 224 | + """ |
| 225 | + |
| 226 | + # can't use `with` because we need wavefile to remain open after return |
| 227 | + self.wavfile = open(file_name, "rb") |
| 228 | + wavedata = audiocore.WaveFile(self.wavfile) |
| 229 | + self.audio.play(wavedata) |
| 230 | + if not wait_to_finish: |
| 231 | + return |
| 232 | + while self.audio.playing: |
| 233 | + pass |
| 234 | + self.wavfile.close() |
| 235 | + |
| 236 | + def stop_play(self): |
| 237 | + """Stops playing a wav file.""" |
| 238 | + self.audio.stop() |
| 239 | + if self.wavfile is not None: |
| 240 | + self.wavfile.close() |
0 commit comments