Toggling Audio in Code (Can't hear music)

I’m trying to figure out how to use AudioComponents in code. I wanted to see if I could toggle some sound. Google shows several BP answers, but I want C++ answers.

I generated a new FirstPerson project in C++ and added some lines of code to the character file. In the project, I created an Input tied to Q, to just hold and release to have sound play while pressed. I’m just posting code that I added, not the whole file since its just the default FPS project.

In the .h file

UCLASS(config=Game)
class ACodeFirstPersonCharacter : public ACharacter
{
	...
public:
	class UAudioComponent* MyAudioComponent;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Test)
	class USoundBase* MySound;

protected:

	void StartSound();
	void StopSound();
	...
};

In the .cpp file

ACodeFirstPersonCharacter::ACodeFirstPersonCharacter()
{
        ...
	MyAudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("AudioTest"));
	MyAudioComponent->AttachParent = GetMesh1P();
	MyAudioComponent->SetSound(MySound);
}

//////////////////////////////////////////////////////////////////////////
// Input

void ACodeFirstPersonCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
	...
	InputComponent->BindAction("Sound", IE_Pressed, this, &ACodeFirstPersonCharacter::StartSound);
	InputComponent->BindAction("Sound", IE_Released, this, &ACodeFirstPersonCharacter::StopSound);
}
...
void ACodeFirstPersonCharacter::StartSound()
{
	MyAudioComponent->Play();
}

void ACodeFirstPersonCharacter::StopSound()
{
	MyAudioComponent->Stop();
}

I downloaded some small music file from the internet and imported it as a wav file, and in the editor assigned it to the variable MySound. I had put some debug messages in the Start and Stop functions to see if it was working correctly with the button press. It works fine that way, but I’m not hearing in music. I’m sure I missed something somewhere, but don’t know what.

I figured out what the problem was. Even though I was assigning a sound to the component in the editor, it wasn’t assigning it to the sound. I also forgot to change bAutoActivate to false. So this little exercise worked the way I expected.

Code in cpp file should be this. For anyone search later on how to attach audiocomponents with sound in code.

ACodeFirstPersonCharacter::ACodeFirstPersonCharacter()
 {
	static ConstructorHelpers::FObjectFinder<USoundBase> Sound(TEXT("SoundWave'/Game/FirstPerson/Audio/dungeonwav.dungeonwav'"));
	MySound = Sound.Object;
	MyAudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("AudioTest"));
	MyAudioComponent->AttachParent = GetMesh1P();
	MyAudioComponent->SetSound(MySound);
	MyAudioComponent->bAutoActivate = false;
 }

Awesome. Thanks for posting your solution for others :slight_smile:

Didn’t work for me :frowning:
Neither this, nor Play(), Activate() or Activate(true).