首页 > 解决方案 > 有没有办法无延迟地播放声音?

问题描述

我的程序正在播放声音PlaySound

该程序运行良好,我可以听到声音,但是当歌曲结束时,有大约 1 秒的延迟,然后歌曲再次播放。

我问了谷歌,他给了我这个问题 - PlaySound() 延迟

回答的那个人说,SND_SYNC我们需要使用SND_ASYNC,我听他说做了,但我什么也听不见。

你有什么建议吗 ?

顺便说一句,这是我目前用于这个项目的歌曲 - Nyan Cat

我希望这首歌会立即重新开始,因为用户不会听到有延迟。

最终代码:

#include <iostream>
#include <Windows.h>
#include <string>
#pragma comment(lib, "winmm.lib")

int main()
{
    std::string pathtosound = "C:\\Users\\roile\\Documents\\Dragonite\\nyan.wav";
    while (true) {
        PlaySound(pathtosound.c_str(), 0, SND_SYNC);
    }

    return 0;
}

标签: c++windowswinapi

解决方案


该标志在Microsoft DocsSND_LOOP中描述如下:

声音重复播放,直到再次调用 PlaySound并将pszSound参数设置为NULL。如果设置了此标志,您还必须设置SND_ASYNC标志。

注意最后一句话,因此下面的代码可能会更好:

#include <iostream>
#include <Windows.h>
#include <string>
#pragma comment(lib, "winmm.lib")

int main()
{
    std::string pathtosound = "C:\\Users\\roile\\Documents\\Dragonite\\nyan.wav";
    PlaySound(pathtosound.c_str(), 0, SND_ASYNC | SND_LOOP);
    while (true) {
        // Stop loop at some point
    }
    PlaySound(NULL, 0, 0);  // Stop sample

    return 0;
}

推荐阅读