|
| 1 | +# MP3 playback with tap trigger |
| 2 | +# Works on M4 and nRF52840 based boards with accelerometer or Propmaker |
| 3 | +import time |
| 4 | +import board |
| 5 | +import busio |
| 6 | +import digitalio |
| 7 | +import audioio |
| 8 | +import audiomp3 |
| 9 | +import adafruit_lis3dh |
| 10 | + |
| 11 | +startup_play = False # set to True to play all samples once on startup |
| 12 | + |
| 13 | +# Set up accelerometer on I2C bus |
| 14 | +i2c = busio.I2C(board.SCL, board.SDA) |
| 15 | +int1 = digitalio.DigitalInOut(board.D6) |
| 16 | +accel = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1) |
| 17 | +accel.set_tap(1, 100) # single or double-tap, threshold |
| 18 | + |
| 19 | +# Set up speaker enable pin |
| 20 | +enable = digitalio.DigitalInOut(board.D10) |
| 21 | +enable.direction = digitalio.Direction.OUTPUT |
| 22 | +enable.value = True |
| 23 | + |
| 24 | +speaker = audioio.AudioOut(board.A0) |
| 25 | + |
| 26 | +sample_number = 0 |
| 27 | + |
| 28 | +print("Lars says, 'Hello, CVT Joseph. Tap to play.'") |
| 29 | + |
| 30 | +if startup_play: # Play all on startup |
| 31 | + for i in range(10): |
| 32 | + sample = "/lars/lars_0{}.mp3".format(i) |
| 33 | + print("Now playing: '{}'".format(sample)) |
| 34 | + mp3stream = audiomp3.MP3Decoder(open(sample, "rb")) |
| 35 | + speaker.play(mp3stream) |
| 36 | + |
| 37 | + while speaker.playing: |
| 38 | + time.sleep(0.1) |
| 39 | + enable.value = speaker.playing |
| 40 | + |
| 41 | + |
| 42 | +while True: |
| 43 | + if accel.tapped and speaker.playing is False: |
| 44 | + sample = "/lars/lars_0{}.mp3".format(sample_number) |
| 45 | + print("Now playing: '{}'".format(sample)) |
| 46 | + mp3stream = audiomp3.MP3Decoder(open(sample, "rb")) |
| 47 | + speaker.play(mp3stream) |
| 48 | + sample_number = (sample_number + 1) % 10 |
| 49 | + enable.value = speaker.playing |
0 commit comments