弹奏功能具有不希望的延迟

发布于 2025-01-23 05:58:29 字数 1149 浏览 2 评论 0原文

我希望在开始播放时从内存中播放WAV文件,并尽可能少。当前,在播放它之前,我将WAV资源加载到内存中,以删除每次调用playsounda()时从磁盘上删除不必要的加载。

#include <iostream>
#include <Windows.h>
#include "resource.h"

#pragma comment (lib, "winmm.lib")

int HangOnError(std::string msg) {
    std::cerr << msg << '\n';
    return -1;
}

int main()
{
    HMODULE hModule = GetModuleHandle(NULL);
    HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(IDR_WAVE1), L"WAVE");
    if (!hResource) return HangOnError("hResource is NULL!");

    HGLOBAL hMemory = LoadResource(hModule, hResource);
    if (!hMemory) return HangOnError("hMemory is NULL!");

    DWORD dwSize = SizeofResource(hModule, hResource);
    LPVOID lpAddress = LockResource(hMemory);

    char* bytes = new char[dwSize];
    memcpy(bytes, lpAddress, dwSize);

    while (true) {
        std::getchar();
        std::cout << "SENDING!\n";
        PlaySoundA(bytes, 0, SND_SYNC | SND_MEMORY);
    }
}

目前,我的Windows 10主机上的该解决方案可从调用PlaySounda()并播放结果音频时,可导致约70ms的延迟。在Windows 7机器上,我得到了约40-50ms的延迟。

如何避免(或减少)此延迟? Windows甚至可以吗?理想情况下,它将低于10毫秒。我尝试了诸如DirectSound和Wasapi之类的解决方案,结果较差。

I'm looking to play a WAV file from memory with as little latency as possible when starting the playback. Currently, I'm loading my WAV resource into memory before playing it to remove the unnecessary loading from the disk every time PlaySoundA() is called.

#include <iostream>
#include <Windows.h>
#include "resource.h"

#pragma comment (lib, "winmm.lib")

int HangOnError(std::string msg) {
    std::cerr << msg << '\n';
    return -1;
}

int main()
{
    HMODULE hModule = GetModuleHandle(NULL);
    HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(IDR_WAVE1), L"WAVE");
    if (!hResource) return HangOnError("hResource is NULL!");

    HGLOBAL hMemory = LoadResource(hModule, hResource);
    if (!hMemory) return HangOnError("hMemory is NULL!");

    DWORD dwSize = SizeofResource(hModule, hResource);
    LPVOID lpAddress = LockResource(hMemory);

    char* bytes = new char[dwSize];
    memcpy(bytes, lpAddress, dwSize);

    while (true) {
        std::getchar();
        std::cout << "SENDING!\n";
        PlaySoundA(bytes, 0, SND_SYNC | SND_MEMORY);
    }
}

Currently this solution on my Windows 10 host results in about 70ms of latency from when PlaySoundA() is called and the resulting audio being played. On a Windows 7 machine I get about 40-50ms of latency.

How can I avoid (or reduce) this latency? Is it even possible with Windows? Ideally it'd be under 10ms. I have tried solutions like DirectSound and WASAPI with worse results.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文