#include <stdio.h>
// 定义状态机的状态
typedef enum {
IDLE,
PLAYING_NOTE,
PAUSE,
} State;
// 定义音符和对应的持续时间
typedef struct {
int note;
int duration;
} Note;
// 非阻塞声音播放函数
void nonBlockingPlay(Note* song, int length) {
static int currentNote = 0;
static State state = IDLE;
static int counter = 0;
switch (state) {
case IDLE:
if (currentNote < length) {
// 实际播放音符的逻辑
printf("Playing note %d for %d ms\n", song[currentNote].note,
song[currentNote].duration);
counter = 0;
state = PLAYING_NOTE;
}
break;
case PLAYING_NOTE:
counter++;
if (counter >= song[currentNote].duration) {
// 停止当前音符的播放逻辑
printf("Stopping note %d\n", song[currentNote].note);
counter = 0;
state = PAUSE;
}
break;
case PAUSE:
counter++;
if (counter >= song[currentNote].duration) {
currentNote++;
state = IDLE;
}
break;
}
}
int main() {
// 定义一段简单的音乐
Note song[] = {
{262, 1000}, // C4
{330, 1000}, // E4
{392, 1000}, // G4
{523, 1000}, // C5
};
int length = sizeof(song) / sizeof(song[0]);
// 播放音乐
while (1) {
nonBlockingPlay(song, length);
// 这里可以添加额外的逻辑
}
return 0;
}
音乐蜂鸣器1
于 2023-08-22 13:05:50 首次发布
5358

被折叠的 条评论
为什么被折叠?



