音乐蜂鸣器1

#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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值