扬声器
类: Speaker_Class(来自 M5Unified)
访问: M5Cardputer.Speaker
扬声器支持音调生成、WAV 播放、原始音频输出和音量控制。
生命周期
bool begin(); // 初始化 I2S 并启动后台音频任务
void end(); // 停止并释放 I2S
bool isRunning(); // 后台任务是否正在运行
bool isEnabled(); // 扬声器引脚是否已配置
音调生成
bool tone(float frequency, uint32_t duration = UINT32_MAX,
int channel = -1, bool stop_current_sound = true);
播放正弦波音调。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
frequency |
float |
— | 频率 (Hz) |
duration |
uint32_t |
UINT32_MAX |
持续时间 (ms,默认无限) |
channel |
int |
-1 |
虚拟声道 0–7 (-1 = 自动选择) |
stop_current_sound |
bool |
true |
先停止当前声道的声音 |
成功返回 true。
M5Cardputer.Speaker.tone(440, 500); // A4 音,持续 500ms
M5Cardputer.Speaker.tone(1000); // 1kHz,持续播放直到停止
M5Cardputer.Speaker.tone(220, 300, 2); // 在声道 2 上播放
高级音调
使用自定义波形数据时,使用完整签名:
音量
void setVolume(uint8_t master_volume); // 主音量 0–255
uint8_t getVolume(); // 获取当前主音量
void setChannelVolume(uint8_t channel, uint8_t volume); // 单声道 0–255
uint8_t getChannelVolume(uint8_t channel); // 获取声道音量
void setAllChannelVolume(uint8_t volume); // 设置全部 8 个声道
停止
WAV 播放
bool playWav(const uint8_t* wav_data, size_t data_len = ~0u,
uint32_t repeat = 1, int channel = -1,
bool stop_current_sound = false);
从 WAV 缓冲区播放音频(含文件头)。将 data_len 设为 ~0u 可从文件头自动检测。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
wav_data |
const uint8_t* |
— | WAV 数据缓冲区指针 |
data_len |
size_t |
~0u |
缓冲区长度(省略则从文件头自动检测) |
repeat |
uint32_t |
1 |
重复次数 |
channel |
int |
-1 |
虚拟声道 0–7 |
stop_current_sound |
bool |
false |
先停止当前声音 |
原始音频
// 有符号 8 位
bool playRaw(const int8_t* data, size_t len, uint32_t sample_rate = 44100,
bool stereo = false, uint32_t repeat = 1,
int channel = -1, bool stop_current_sound = false);
// 无符号 8 位
bool playRaw(const uint8_t* data, size_t len, uint32_t sample_rate = 44100,
bool stereo = false, uint32_t repeat = 1,
int channel = -1, bool stop_current_sound = false);
// 有符号 16 位
bool playRaw(const int16_t* data, size_t len, uint32_t sample_rate = 44100,
bool stereo = false, uint32_t repeat = 1,
int channel = -1, bool stop_current_sound = false);
查询播放状态
bool isPlaying() const; // 任意声道是否正在播放
size_t isPlaying(uint8_t channel) const; // 单声道: 0=空闲, 1=播放中(队列有空间), 2=播放中(队列满)
size_t getPlayingChannels() const; // 当前活跃声道数
快速示例
// 启动提示音
M5Cardputer.Speaker.setVolume(200);
M5Cardputer.Speaker.tone(800, 100);
delay(100);
M5Cardputer.Speaker.tone(1000, 100);
// 播放旋律
int melody[] = {262, 294, 330, 349, 392, 440, 494, 523};
for (int i = 0; i < 8; i++) {
M5Cardputer.Speaker.tone(melody[i], 150);
delay(150);
}
M5Cardputer.Speaker.stop();