2020年5月12日 星期二

Week12-聲音、音效、音樂,播放 WAV檔、 MP3檔


W12-01-WAV

打開glut專案,裝好freeglut
google"WAV download"一個音檔到bin資料夾


~~執行後的結果~~

滑鼠點一下視窗會發出槍聲

~~程式碼~~
#include <GL/glut.h>///GLUT
#include <windows.h>///為了一些定義DWORD
#include <mmsystem.h>///為了PlaySoundA()
void display()
{   
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);   
 glutSwapBuffers();
}
void mouse(int button,int state,int x,int y)
{///讓mouse點一下發出聲音        
if(state==GLUT_DOWN)       
 PlaySoundA("ak47.wav",NULL,SND_SYNC);///MP3音檔
}
int main(int argc,char**argv)
{    
glutInit(&argc,argv);  
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);   
glutCreateWindow("Week12 sound");///視窗標題  
glutMouseFunc(mouse);    
glutDisplayFunc(display);    
glutMainLoop();
}

W12-02-MP3

下載解壓縮 "CMP3" 到 codeblocks 的專案內

到youtube找一首歌用MP3轉換器  轉成MP3
再放到bin資料夾中

~執行後的結果~
會自動播放MP3"天黑請閉眼"的音樂
滑鼠點視窗也可以同時聽到AK47的槍聲

~~程式碼~~
#include <GL/glut.h>///GLUT
#include <windows.h>///為了一些定義DWORD
#include <mmsystem.h>///為了PlaySoundA()
#include "CMP3_MCI.h"///雙引號,表示要在同一個專案目錄找
CMP3_MCI myMP3;///宣告一個物件變數myMP3
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSwapBuffers();
}
void mouse(int button,int state,int x,int y)
{///讓mouse點一下發出聲音
        if(state==GLUT_DOWN)
        PlaySoundA("ak47.wav",NULL,SND_SYNC);///MP3音檔
}
int main(int argc,char**argv)
{
    myMP3.Load("天黑請閉眼.mp3");///讀入檔案,執行目錄
    myMP3.Play();///Mp3播放
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week12 sound");///視窗標題

    glutMouseFunc(mouse);
    glutDisplayFunc(display);
    glutMainLoop();
}

W12-03-GLUT .cbp 專案設定 


打開我的專案的NotePad++
修改程式碼>讓原先設定的要把檔案放在freeglut的bin中
修改成可以放到 "." 任何地方


 將原本在bin中的3個音檔剪下放到我的專案中

~~執行看看結果,一樣可以播放MP3跟WAV檔~~

W12-03-鍵盤操控撥放音樂

複製音檔到我的專案中
加入keyboard函式操控音樂
~執行後就完成了~
~程式碼~
#include <GL/glut.h>///GLUT
#include <windows.h>///為了一些定義DWORD
#include <mmsystem.h>///為了PlaySoundA()
#include "CMP3_MCI.h"///雙引號,表示要在同一個專案目錄找
CMP3_MCI myMP3;///宣告一個物件變數myMP3
CMP3_MCI Do,Re,Mi,Fa,So;
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSwapBuffers();
}
void keyboard(unsigned char key,int x,int y)
{
    if(key=='1')Do.Play();
    if(key=='2')Re.Play();
    if(key=='3')Mi.Play();
    if(key=='4')Fa.Play();
    if(key=='5')So.Play();
}
void mouse(int button,int state,int x,int y)
{///讓mouse點一下發出聲音
        if(state==GLUT_DOWN)
        PlaySoundA("ak47.wav",NULL,SND_SYNC);///MP3音檔
}
int main(int argc,char**argv)
{
    Do.Load("do.wav"); Re.Load("re.wav"); Mi.Load("mi.wav");
    Fa.Load("fa.wav"); So.Load("so.wav");
    myMP3.Load("music.mp3");///讀入檔案,執行目錄
    myMP3.Play();///Mp3播放
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week12 sound");///視窗標題

    glutMouseFunc(mouse);
    glutKeyboardFunc(keyboard);
    glutDisplayFunc(display);
    glutMainLoop();
}

沒有留言:

張貼留言