|
| 1 | +# SPDX-FileCopyrightText: 2023 ladyada for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +# Demo audio player that plays random wav files from internal storage or |
| 6 | +# SD card. Default pinout matches the Audio BFF for QT Py S2, S3 and RP2040 |
| 7 | + |
| 8 | +import os |
| 9 | +import time |
| 10 | +import audiocore |
| 11 | +import board |
| 12 | +import audiobusio |
| 13 | +import audiomixer |
| 14 | +import adafruit_sdcard |
| 15 | +import storage |
| 16 | +import digitalio |
| 17 | +import random |
| 18 | + |
| 19 | +card_cs = digitalio.DigitalInOut(board.A0) |
| 20 | +card_cs.direction = digitalio.Direction.INPUT |
| 21 | +card_cs.pull = digitalio.Pull.UP |
| 22 | +sdcard = None |
| 23 | + |
| 24 | +DATA = board.A1 |
| 25 | +LRCLK = board.A2 |
| 26 | +BCLK = board.A3 |
| 27 | +audio = audiobusio.I2SOut(BCLK, LRCLK, DATA) |
| 28 | +mixer = None |
| 29 | + |
| 30 | +button = digitalio.DigitalInOut(board.BUTTON) |
| 31 | +button.switch_to_input(pull=digitalio.Pull.UP) |
| 32 | + |
| 33 | +wave_files = [] |
| 34 | +for filename in sorted(os.listdir("/")): |
| 35 | + filename = filename.lower() |
| 36 | + if filename.endswith(".wav") and not filename.startswith("."): |
| 37 | + wave_files.append(filename) |
| 38 | + |
| 39 | +while True: |
| 40 | + if not sdcard: |
| 41 | + try: |
| 42 | + sdcard = adafruit_sdcard.SDCard(board.SPI(), card_cs) |
| 43 | + vfs = storage.VfsFat(sdcard) |
| 44 | + storage.mount(vfs, "/sd") |
| 45 | + print("Mounted SD card") |
| 46 | + wave_files = ["/"+file for file in os.listdir('/') if file.endswith('.wav')] |
| 47 | + wave_files += ["/sd/"+file for file in os.listdir('/sd') if file.endswith('.wav')] |
| 48 | + print(wave_files) |
| 49 | + except OSError: |
| 50 | + pass |
| 51 | + |
| 52 | + if not button.value: |
| 53 | + if mixer and mixer.voice[0].playing: |
| 54 | + print("stopping") |
| 55 | + mixer.voice[0].stop() |
| 56 | + if wavefile: |
| 57 | + wavefile.close() |
| 58 | + else: |
| 59 | + name = random.choice(wave_files) |
| 60 | + print("playing", name) |
| 61 | + wavefile = open(name, "rb") |
| 62 | + wave = audiocore.WaveFile(wavefile) |
| 63 | + mixer = audiomixer.Mixer(voice_count=1, |
| 64 | + sample_rate=wave.sample_rate, |
| 65 | + channel_count=wave.channel_count, |
| 66 | + bits_per_sample=wave.bits_per_sample, |
| 67 | + samples_signed=True) |
| 68 | + mixer.voice[0].level = 0.1 |
| 69 | + audio.play(mixer) |
| 70 | + mixer.voice[0].play(wave) |
| 71 | + |
| 72 | + while not button.value: |
| 73 | + pass |
0 commit comments