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.