I'd like to use this function to call the the PlaySoundA function, but the sound file I am trying to play does not open.
void AudioClass::playAudio(const char* incomingData, const char* filePath)
{
char buffer[100]; // <- danger, only storage for 100 characters.
strncpy_s(buffer, filePath, sizeof(buffer));
strncat_s(buffer, incomingData, sizeof(buffer));
PlaySoundA(buffer, NULL, SND_FILENAME);
}
As I found out, if the argument for the LPCSTR pszSound parameter of PlaySoundA() is given as a string (e.g. "C:/Users/User/Documents/sound.wav"), i.e. the full path of the file is given, the sound will play.
I would like to combine the incomingData parameter (file name) and the filePath parameter, for which I used a buffer.
If the file cannot be found, the default system sound should play (it was a beep in my case), but this is no longer the case; even though SND_NODEFAULT flag was not set, in which case PlaySoundA() would return silently, without playing the default system sound.
https://learn.microsoft.com/en-us/previous-versions/dd743680(v%3Dvs.85)
Is it possible that the argument I am trying to pass in not compatible with LPCSTR pszSound parameter?
While running the debugger, the buffer variable seems to hold the whole path (C:/Users/User/Documents/sound.wav\r\n), but why is there a \r\n prefix at the end?
Definitions:
#define MAX_DATA_LENGTH 255
char incomingData[MAX_DATA_LENGTH];
const char* filePath {"C:/Users/User/Desktop/"};
//Arduino SerialPort object
SerialPort *arduino;
//Audio file AudioClass object
AudioClass* audio;
playAudio() is called here:
void exampleReceiveData(void)
{
int readResult = arduino->SerialPort::readSerialPort(incomingData, MAX_DATA_LENGTH);
audio->AudioClass::playAudio(incomingData, filePath);
Sleep(10000);
}
EDIT_1: the length of the real file path I use is shorter than 100 characters.
EDIT_2: I get this warning: String 'buffer' might not be zero-terminated.
The \r\n
at the end comes from the serial port: https://www.arduino.cc/reference/en/language/functions/communication/serial/println
You can skip the characters when copying:
strncat_s(buffer, incomingData, strnlen(incomingData) - 2);