PLOW
PLOW

Reputation: 379

Windows Form sound file does not exist and how to retrieve embedded sound (C++)

The sound file is located on my project folder and I added the sound file to my Resource Files.
I don't get any error when I run the debugger within visual studio 2012.
I get the error when I run the application located in the Debug folder.

However, I don't get any errors when I include the file location directory path.

Sound file not located

namespace FORMv2 {

    //omitted code

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             player = gcnew SoundPlayer;
             //no error
             //player->SoundLocation = "c/<path goes here>/soundBit.wav";
             // error
             player->SoundLocation = "soundBit.wav";
             player->PlayLooping();
         }    
private: System::Void checkBoxEnable_CheckedChanged(System::Object^  sender, System::EventArgs^  e) {
             if (checkBoxEnable->Checked)
             {
                 player->Stop();    
             }
             else
             {
                 player->Play();    
             }           
         }
    };
}

Upvotes: 1

Views: 394

Answers (2)

imirica
imirica

Reputation: 11

Include your files in the project`s resources folder by right-clicking on your project name>>properties>>Recources>>select audio>>drag your .wav file.

Then you can play the file from Memory Stream:

public void Play()
{
    SoundPlayer player = new SoundPlayer();
    player.Stream = YOUR_PROJECT_NAME.Properties.Resources.YOUR_FILE_NAME;
    player.Play();
}

Solution taken from : Please be sure a sound file exists at the specified location

Upvotes: 0

PLOW
PLOW

Reputation: 379

I was able to figure it out.
I found this website:
https://msdn.microsoft.com/en-us/library/system.windows.forms.application.startuppath%28v=vs.110%29.aspx
which gave me the path to where the application is. I moved the .wav file to that path and added the following statement:

player->SoundLocation = String::Concat(Application::StartupPath+"/soundBit.wav");

Edit:
Found a better way and that was to embed the sound to Form1.resX and
retrieve the embedded sound.
I had to changed the name of the file to "$this.soundBit" and add this code:

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             ComponentResourceManager^  resources = (gcnew ComponentResourceManager(Form1::typeid));
             SoundPlayer^ player;
             Stream^ s = (cli::safe_cast<MemoryStream^ >(resources->GetObject(L"$this.soundBit")));
             player = gcnew SoundPlayer(s);
             player->Play();        
         }

and this namespaces:

using namespace System::ComponentModel; // For ComponentResourceManager
using namespace System::Media; // For SoundPlayer
using namespace System::IO; // For MemoryStream

Upvotes: 1

Related Questions