2013-07-31 94 views
0

我正在編寫一個C函數來播放wav文件。我可以播放一次聲音,但我想添加一個循環選項。PlaySound函數奇怪的行爲

我有兩個工作模式:從文件名

  • 發揮
  • 發揮從內存中。

在這兩種模式下,我都無法播放超過兩次的聲音,此後功能崩潰。

注:I解決添加此的代碼:

BOOL WINAPI PlaySound(LPCSTR,HMODULE,DWORD);

沒有它我得到的問題。

我的代碼:

#include <windows.h> 
#include <stdio.h> 

void play(char * fileName, int repeat); 
char* file2vector(char* fileName, long int* size); 

int main(int argc, char ** argv) 
{ 
    if (argc > 1) { 
     play(argv[1], 5); 
    } 

} 


void play(char * fileName, int repeat) 
{ 
#define SND_SYNC 0 
#define SND_ASYNC 1 
#define SND_FILENAME 0x20000 
#define SND_NODEFAULT 2 
#define SND_MEMORY 4 
#define SND_NOSTOP 16 

    int mode = SND_SYNC | SND_NODEFAULT | SND_NOSTOP; 
    char * sound; 
    int play = 1; 
    int i; 

    long int size; 
    unsigned char* wavFile = file2vector(fileName, &size); 

    if (wavFile == NULL) { 
     mode |= SND_FILENAME; 
     sound = fileName; 
     printf("filename\n"); 
    } 
    else { 
     mode |= SND_MEMORY; 
     sound = wavFile; 
     printf("memory\n"); 

    } 


    if (repeat) { 
     play += repeat; 
    } 

    printf("play %d times\n", play); 

    int res; 
    for (i = 1; i <= play; ++i) { 
     printf("played %i\n", i); 
     res = PlaySound(sound, NULL, mode); 
     printf("res:%d\n", res); 
    } 

    PlaySound(NULL, 0, 0); 
    free(wavFile); 

    printf("ready"); 


} 

char* file2vector(char* fileName, long int* size) 
{ 
    char* vector = NULL; 
    FILE* file = fopen(fileName, "rb"); 

    if (NULL == file) { 
     *size = 0L; 
    } 
    else 
    { 
     fseek(file, 0L, SEEK_END); 
     *size = ftell(file); 
     fseek(file, 0L, SEEK_SET); 

     /* ftell can return -1 on failure */ 
     if (*size <= 0) { 
      *size = 0L; 

     } 
     else 
     { 
      vector = (char*)malloc(*size); 
      if (NULL != vector) { 
       fread(vector, sizeof(char), *size, file); 
      } 
     } 

     fclose(file); 
    } 

    return vector;  
} 

當我運行這段代碼,例如:

pplay.exe c:\windows\media\chimes.wav 

它打印:

memory 
play 6 times 
played 1 
res:1 
played 2 
res:1 
played 4198705 
+0

當你通過你的循環時,調試器顯示你什麼? –

回答

0

在我的電腦上的代碼工作正常。即使我多次播放文件。 輸出:

C:\Users\avesudra\*****\***\*****\example\bin\Debug>example.exe c:\windows\media\chimes.wav 
memory 
play 8 times 
played 1 
res:1 
played 2 
res:1 
played 3 
res:1 
played 4 
res:1 
played 5 
res:1 
played 6 
res:1 
played 7 
res:1 
played 8 
res:1 
ready

這很奇怪。如果你願意,你可以從這裏下載這個可執行文件來嘗試它,看看是否有效: https://www.dropbox.com/s/iphluu1huzq48vk/example.exe

+0

謝謝。我使用微小的c,我添加了這個頭文件,現在我編譯並運行正常,沒有它,它在運行時執行失敗。 BOOL WINAPI PlaySound(LPCSTR,HMODULE,DWORD); – carlos

+0

很奇怪我的代碼是在gcc上編譯的,可能是編譯器,但我不知道。 – avesudra

+0

也許這是以前用錯誤的調用約定調用的? WINAPI位有所不同。 –