gpt4 book ai didi

c - PlaySound 功能奇怪的行为

转载 作者:行者123 更新时间:2023-11-30 17:49:15 24 4
gpt4 key购买 nike

我正在用 C 编写一个函数来播放 wav 文件。我可以播放一次声音,但我想添加一个循环选项。

我有两种工作模式:

  • play from file name
  • play from memory.

在两种模式下,我都无法播放声音超过两次,之后函数就会崩溃。

注意:我解决了将其添加到代码中的问题:

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

最佳答案

在我的电脑上,代码运行正常。即使我多次播放该文件。输出为:

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

这很奇怪。如果需要,您可以从此处下载该可执行文件来尝试并查看是否有效: https://www.dropbox.com/s/iphluu1huzq48vk/example.exe

关于c - PlaySound 功能奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17980319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com