這次我們要在GLUT裡播放聲音

首先先隨便下載一個.wav聲音檔:
http://billor.chsh.chc.edu.tw/sound/boom.htm
接著下載他然丟到freeglut資料夾裡的bin
程式碼: (基本上幾乎都是原本畫圖時會用到的程式)
#include <GL/glut.h>
#include <windows.h>
#include <mmsystem.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glutSwapBuffers();
}
void mouse(int button, int state,int x, int y)
{
if(state==GLUT_DOWN)PlaySoundA("boom.wav",NULL,SND_SYNC); ///播放聲音的程式
}
int main(int argc,char**argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_DEPTH);
glutCreateWindow("Week12");
glutMouseFunc(mouse);
glutDisplayFunc(display);
glutMainLoop();
}
執行時只要點黑色畫面就可以播放了,注意:因為有按下和鬆開所以會發出兩次聲音
-----------------------------------
如果想再加入背景音樂呢?
可以,先下載一個叫CMP3_MCI的檔案,放在主專案資料夾(今天指week11)
下載你想要的MP3,一樣丟到freeglut資料夾裡的bin
然後再加這些程式碼:
#include <GL/glut.h>
#include <windows.h>
#include <mmsystem.h>
#include "CMP3_MCI.h" ///開啟這個檔案
CMP3_MCI myMP3; ///宣告額外的元件
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glutSwapBuffers();
}
void mouse(int button, int state,int x, int y)
{
if(state==GLUT_DOWN)PlaySoundA("boom.wav",NULL,SND_ASYNC);
}
int main(int argc,char**argv)
{
myMP3.Load("music.mp3"); ///載入MP3
myMP3.Play(); ///播放MP3
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_DEPTH);
glutCreateWindow("Week12");
glutMouseFunc(mouse);
glutDisplayFunc(display);
glutMainLoop();
}
這樣的話,當程式在跑的時候背景音樂會播放,按滑鼠時也會有聲音了

順便一提,當較小的視窗被關閉時全部的聲音也會停止

#include <windows.h>
#include <mmsystem.h>
#include "CMP3_MCI.h" ///開啟這個檔案
CMP3_MCI myMP3; ///宣告額外的元件
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glutSwapBuffers();
}
void mouse(int button, int state,int x, int y)
{
if(state==GLUT_DOWN)PlaySoundA("boom.wav",NULL,SND_ASYNC);
}
int main(int argc,char**argv)
{
myMP3.Load("music.mp3"); ///載入MP3
myMP3.Play(); ///播放MP3
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_DEPTH);
glutCreateWindow("Week12");
glutMouseFunc(mouse);
glutDisplayFunc(display);
glutMainLoop();
}
這樣的話,當程式在跑的時候背景音樂會播放,按滑鼠時也會有聲音了

順便一提,當較小的視窗被關閉時全部的聲音也會停止

沒有留言:
張貼留言