C语言播放音乐(DOS)

来源:互联网 发布:软件实施服务合同范本 编辑:程序博客网 时间:2024/05/20 16:33

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <mmsystem.h>
#pragma comment(lib,"winmm.lib")
#include <string>
using namespace std;

char buf[50];
MCIERROR mcierror;
string song_name,mci_string;
char time_all[60];
int dwlong;
bool first_song=true;

void play();

void main()
{
 song_name="cg.mp3";
 first_song=false;
 play();
    while (1)
    {   
     mciSendString("status 设备1 position",buf,sizeof(buf),NULL);//获取播放歌曲的进度,
     int position=atoi(buf);//转化为整型数据
     printf("当前进度:%d\r",position);
     if(position>=dwlong)
     {
      mciSendString("close 设备1",buf,sizeof(buf),NULL); //这一布至关重要,要先把已经播放完的设备先关闭,因为不能够出现同名的设备名"设备1"!!
      if (first_song==false)
      {
       song_name="cg.mp3";
       first_song=true;
      
      }
      else
      {
       song_name="cg.mp3";
       first_song=false;
      }
      position=0;
      system("cls");
      play();
      
     } 
     Sleep(1000);//Sleep()的功能是让主调进程休息一个时间段执行睡眠,时间段过后继续调度,参数是毫秒级,1000毫秒=1秒,在这里是每隔一秒刷新一次显示频...
    }
   
   
}

void play()
{
 mci_string="open "+song_name+" alias 设备1"; 
 mcierror=mciSendString(mci_string.c_str(),buf,50,NULL);//命令"open 1.mp3  alias 设备1"也可以写成"open 1.mp3 type mpegvideo alias 设备1",不写的话系统会自己寻找对应设备。"alias 设备1"是另外起名为设备1,以后播放的时候直接用"设备1"即可。
 if (mcierror)
 {
  mciGetErrorString(mcierror,buf,strlen(buf));
  printf("%s",buf);
  return;
 }
 mciSendString("set 设备1 time format TMSF",buf,50,NULL);//设置时间格式为分秒格
 mciSendString("status 设备1 length ",buf,sizeof(buf),NULL); //获取歌曲长度信息
 dwlong=atoi(buf);//把时间转化为整数。
 printf("歌曲名称:%s\n歌曲长度:%d\n",song_name.c_str(),dwlong);
 mciSendString("play 设备1 repeat",buf,50,NULL);//如果要单首歌曲循环播放。"play 设备1 repeat"
 
}

原创粉丝点击