PlaySound not playing sound
Apr 15, 2021 at 6:49pm UTC
I'm trying to use PlaySound to play back a WAV audio file. I can hear the audio when I reference the WAV file directly but can't hear anything when I try to play it from memory. Here's what I have:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <mmsystem.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
class Wave {
public :
Wave(string filename);
~Wave();
void play(bool async = true );
bool isok();
private :
wchar_t * buffer;
bool ok;
HINSTANCE HInstance;
};
Wave::Wave(string filename)
{
ok = false ;
buffer = 0;
HInstance = GetModuleHandle(0);
std::wifstream infile(filename, std::ios::binary);
if (!infile)
{
std::cout << "Wave::file error: " << filename << std::endl;
return ;
}
infile.seekg(0, std::ios::end); // get length of file
ULONGLONG length = infile.tellg();
buffer = new wchar_t [length]; // allocate memory
infile.seekg(0, std::ios::beg); // position to start of file
infile.read(buffer, length); // read entire file
infile.close();
ok = true ;
}
Wave::~Wave()
{
PlaySound(NULL, 0, 0); // STOP ANY PLAYING SOUND
delete [] buffer; // before deleting buffer.
}
void Wave::play(bool async)
{
if (!ok)
return ;
if (async)
PlaySound(buffer, HInstance, SND_MEMORY | SND_ASYNC);
else
PlaySound(buffer, HInstance, SND_MEMORY);
}
bool Wave::isok()
{
return ok;
}
I then use:
Wave audio("may_wav_file_name.WAV");
audio.play();
... crickets :)
Last edited on Apr 15, 2021 at 7:37pm UTC
Apr 15, 2021 at 6:52pm UTC
This post is in the wrong forum, it should really be in the Windows forum or the Lounge.
When you are done reading this message, send me a PM so I can delete it. Then you can delete your message and repost in the Lounge.
Apr 16, 2021 at 3:05am UTC
Fixed: changed from wide char to char and cast buffer to LPCTSTR:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
SoundFX::SoundFX(string filename)
{
ok = false ;
buffer = 0;
HInstance = GetModuleHandle(0);
ifstream infile(filename, ios::binary);
if (!infile)
{
cout << "Wave::file error: " << filename << endl;
return ;
}
infile.seekg(0, ios::end); // get length of file
ULONGLONG length = infile.tellg();
buffer = new char [length]; // allocate memory
infile.seekg(0, ios::beg); // position to start of file
infile.read(buffer, length); // read entire file
infile.close();
ok = true ;
}
void SoundFX::play(bool async)
{
if (!ok)
return ;
if (async)
PlaySound((LPCTSTR)buffer, HInstance, SND_MEMORY | SND_ASYNC);
else
PlaySound((LPCTSTR)buffer, HInstance, SND_MEMORY);
}
bool SoundFX::isok()
{
return ok;
}
Topic archived. No new replies allowed.