How play a wave sound in C++[SOLVED]

Hi Everyone!
I’m trying to use the PlaySound2D() in C++ but I’m quite confused on what parameters pass to this method.
More preciserly I don’t know how to create the USoundBase argument.
I have a *.wav audio that must be played, so I’ve created a USoundWave object, but then I don’t know how to tell to it where to get the sound. I’ve seen that there’s the function USoundWave::InitAudioResource(), what should I pass to it?

Doesn’t anybody know?

Thanks a lot!

I did it!
Actually it was pretty easy, here’s the solution:

After importing the audio *.wav through the editor, go in the UObject that will have the audio member and declare a USoundWave member

UCLASS()
class MYPROJECT_API UMyUObject : public UObject
{
	GENERATED_BODY()

	UPROPERTY()
		class USoundWave* MySoundWave;

etc...
}

Next go in the constructor implementation

UMyUObject::UMyUObject()
{
	// Init Audio Resource
	static ConstructorHelpers::FObjectFinder<USoundWave> myAudioResource(TEXT("<Reference_Path>"));
	MatchReadyAudioWave = matchReadyAudioResource.Object;
MySoundWave = myAudioResource.Object;
}

To get the <Reference_Path> just right click on your file in the editor and select “Copy Reference”

Now your audio is ready to be played! here’s an example

UMyUObject::PlayAudio()
{
	UGameplayStatics::PlaySound2D(this, MySoundWave);
}

You can play with PlaySound2d arguments to have some control on the reproduced audio!

I’m using this for UI, so I think that’s quite a powerfull solution since the location of the sound source isn’t relevant at all!

Have fun!

2 Likes