Download

SpawnSound2D repeatedly plays a sound over and over

hey guys i’m trying to play a walking sound when the player is pressing the forward button I’m using spawnsound2D function to do so but there’s a problem and that is instead of playing the sound and waiting for it to finish the function is being called everyframe so it makes a horrible noise. here is the code

void AFirstPerson::MoveForward(float Amount)
{
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation = FRotator(0, Rotation.Yaw, 0);

const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
AddMovementInput(Direction, Amount);

if (Amount != 0.0f)
{
PlaySound = true;
if (WalkingSound && PlaySound)
{
UGameplayStatics::SpawnSound2D(this, WalkingSound);
UE_LOG(LogTemp, Warning, TEXT(“Playing Sound”));
}
}

if (Amount == 0.0f)
{
PlaySound = false;
UE_LOG(LogTemp, Warning, TEXT(“Stopping Sound”));

}
}

There are several ways to do it. But since you want to spawn the sound everytime you move forward, then:

1 - set the sound to loop:

](filedata/fetch?id=1803875&d=1598117942)

2 - spawn the sound and stop it when not moving:

in .h file:



class UAudioComponent* walk_sound = nullptr;


in .cpp file:



void AFPCPPCharacter::MoveForward(float Value)
{
    if (Value != 0.0f)
   {
      AddMovementInput(GetActorForwardVector(), Value);

      if (WalkingSound && !IsValid(walk_sound))
      {
         walk_sound = UGameplayStatics::SpawnSound2D(this, WalkingSound);
         UE_LOG(LogTemp, Warning, TEXT("Playing Sound"));
      }
   }
   else
   {
      if (IsValid(walk_sound))
      {
         walk_sound->Stop();
         UE_LOG(LogTemp, Warning, TEXT("Stop Sound"));
      }
   }
}


PS: Also, about your code, the PlaySound in this check is useless since it’s always true:



if (WalkingSound && PlaySound)