Micro:Bit结合MicroPython能否存储歌曲并在特定场景触发播放?
Absolutely! This is totally doable with MicroPython on the micro:bit—here's a step-by-step breakdown to make it happen:
核心原理
The micro:bit can generate PWM (Pulse Width Modulation) signals through its GPIO pins to drive a speaker, and you can store song data directly in your MicroPython code as a list of note frequencies and durations. Triggering playback via the A button is straightforward with the micro:bit's built-in button input functions.
完整代码示例(基础版)
This example uses direct pin control to play a simple version of "Twinkle Twinkle Little Star" when the A button is pressed:
from microbit import * # 定义歌曲:每个元素是(音符频率Hz, 播放时长毫秒) STAR_SONG = [ (262, 500), (262, 500), (392, 500), (392, 500), (440, 500), (440, 500), (392, 1000), (349, 500), (349, 500), (330, 500), (330, 500), (294, 500), (294, 500), (262, 1000) ] def play_song(song): for note_freq, duration in song: # 驱动扬声器(假设扬声器接引脚0和GND) pin0.write_analog(512) # 50%占空比,保证合适音量 pin0.set_analog_period(int(1000000 / note_freq)) # 计算音符周期(微秒) sleep(duration) pin0.write_analog(0) # 停止发声 sleep(50) # 音符间的短暂停顿,让旋律更清晰 while True: if button_a.is_pressed(): play_song(STAR_SONG) # 等待按键释放,避免重复触发播放 while button_a.is_pressed(): sleep(10)
简化版:使用audio模块
MicroPython for micro:bit includes an audio module with pre-defined note constants, making your code more readable:
from microbit import * import audio # 用预定义音符常量定义歌曲,更直观 STAR_SONG = [ (audio.NOTE_C4, 500), (audio.NOTE_C4, 500), (audio.NOTE_G4, 500), (audio.NOTE_G4, 500), (audio.NOTE_A4, 500), (audio.NOTE_A4, 500), (audio.NOTE_G4, 1000), (audio.NOTE_F4, 500), (audio.NOTE_F4, 500), (audio.NOTE_E4, 500), (audio.NOTE_E4, 500), (audio.NOTE_D4, 500), (audio.NOTE_D4, 500), (audio.NOTE_C4, 1000) ] def play_song(song): for note, duration in song: audio.play(audio.Note(note, duration)) sleep(50) while True: if button_a.was_pressed(): play_song(STAR_SONG)
关键细节提示
- 扬声器接线: Connect one terminal of your speaker to pin 0 and the other to GND. For louder audio, you can add a simple transistor amplifier circuit between the micro:bit and speaker.
- 歌曲存储: The micro:bit has enough memory to store multiple short songs as lists. For longer tracks, you could use external storage (like an SD card via I2C), but this is overkill for most simple projects.
- 扩展触发场景: You can easily modify the code to trigger playback from other inputs—like shaking the micro:bit, detecting light levels, or receiving a radio signal.
内容的提问来源于stack exchange,提问作者user10420480

