'The PlaySound function has undesired latency
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|