play .wav file using c language

5.2k views Asked by At

I was asked to play .wav files using C language, the compiler I'm using is Devcpp. I was trying to use the function PlaySound() as below:

PlaySound("C:/Users/wavfiles/13.1.wav", NULL, SND_FILENAME); 

If I directly input the directory to the function like this, it is able to successfully play the sound.

However, I want to set the directory as a variable. I create a text file with a list of directory and extract the one that I want, then put it into PlaySound() function. Here is part of my code:

FILE *fw;
char addr[1000]
char schapter[50];

while(fgets(addr, 1000, fw) != NULL) {
    if((strstr(addr, schapter)) != NULL) {   
        printf("\n%s", addr);
        PlaySound(addr, NULL, SND_FILENAME); 
    }
}

In this case, the directory is assigned to addr (addr = "C:/Users/wavfiles/13.1.wav") and then I put addr into PlaySound(), but it doesn't work.

I have been stuck on this problem for a long time and cannot move on. I would really appreciate it if anyone can give me suggestions or solutions. Thank you.

1

There are 1 answers

1
AudioBubble On BEST ANSWER

The string returned by fgets() contains the terminal newline. You'll need to remove that to get the filename.

An easy way to do this is to use strchr() to locate the newline:

while (fgets(addr, 1000, fw) != NULL) {
    char *nl = strchr(addr, '\n');
    if (nl) *nl = 0;
    …
}