UE4 播放声音

.h文件

public:    

    UPROPERTY(EditDefaultsOnly, Category = "Sound")
    USoundCue* EngineSound;

    UPROPERTY(VisibleAnywhere,Category="Sound")
    UAudioComponent* AudioComp;

    void PlayEngineSound();

.cpp 文件

//构造函数里面写下面2行

    AudioComp = CreateDefaultSubobject<UAudioComponent>(TEXT("AudioComp"));
    AudioComp->SetupAttachment(RootComponent);
    

void AMyCharacter::BeginPlay()
{
    Super::BeginPlay();
    

    //判断是否合法,要有这个判断,不然程序有可能奔溃
    if (EngineSound->IsValidLowLevelFast())
    {
        AudioComp->SetSound(EngineSound);
        EngineSound->PitchMultiplier = 0.2f; //设置音调
    }
    
}

void AMyCharacter::PlayEngineSound()
{
    if (!AudioComp->IsPlaying())
    {
        AudioComp->Play();
    }
}
 

第二种方法

#include "Sound/SoundCue.h"

#include "Kismet//GameplayStatics.h"

USoundCue* CutTimeSoundCue;

UGameplayStatics::PlaySoundAtLocation(this, CutTimeSoundCue, FVector(0, 0, 0));

猜你喜欢

转载自blog.csdn.net/m0_37981386/article/details/83213762