2017-07-27 42 views
0

我想製作一個計時器,並讓它在最後播放聲音。我做了定時器,它工作正常,但聲音不會播放。這是我到目前爲止有:定時器到零時如何播放聲音?

int main() { 
    //cout << "This is a timer. It is still in the making but it the seconds work properly." << endl; 
    //Sleep(7000); 
    //system("CLS"); 

    int input; 

    cout << "Enter a time: "; 
    cin >> input; 
    cout << endl << "Begin." << endl; 
    system("CLS"); 

    while (input != 0) { 
     input--; 
     cout << input << " seconds" << endl; 
     Sleep(200); 
     system("CLS"); 

     if (input == 0) { 
      PlaySound(TEXT("C:\\Users\\iD Student\\Downloads\\Never_Gonna_Hit_Those_Notes.wav"), NULL, SND_FILENAME | SND_ASYNC); 
     } 
    } 
} 
+3

您正在以異步模式播放聲音。我猜主要在聲音開始播放之前終止。嘗試刪除'SND_ASYNC'。 – DimChtz

+0

謝謝Dim!刪除'SND_ASYNC'修復了它。 –

回答

0

正如其他人所提到的,SND_ASYNC標誌是罪魁禍首,你需要將其刪除。

我也建議你重構你的代碼,將PlaySound()移到循環之外。循環中多次檢查input沒有意義。當循環結束時將會調用循環後的代碼:

const char* plural[] = {"", "s"}; 

int main() 
{ 
    int input; 

    cout << "Enter # of seconds: "; 
    cin >> input; 

    system("CLS"); 
    cout << "Begin." << endl; 

    while (input > 0) 
    { 
     system("CLS"); 
     cout << input << " second" << plural[input != 1] << endl; 
     Sleep(1000); 
     --input; 
    } 

    system("CLS"); 
    cout << "Done." << endl; 

    PlaySound(TEXT("C:\\Users\\iD Student\\Downloads\\Never_Gonna_Hit_Those_Notes.wav"), NULL, SND_FILENAME); 

    return 0; 
} 
-1

獲取末擺脫SND_ASYNC的:

int main() 
{ 
    int input; 

    cout << "Enter a time: "; 
    cin >> input; 
    cout << endl << "Begin." << endl; 
    system("CLS"); 

    while (input != 0) { 
     input--; 
     cout << input << " seconds" << endl; 
     Sleep(200); 
     system("CLS"); 

     if (input == 0) { 
      PlaySound(TEXT("C:\\Users\\iD Student\\Downloads\\Never_Gonna_Hit_Those_Notes.wav"), NULL, SND_FILENAME); 
     } 
    } 
}