播放SoundCue
1,音频文件必须是wav,导入工程后
2,新建一个SoundCue资源:右键 -》 Sounds -》 SoundCue
3,将SoundWave摔了拖入编辑器,并连接上Output节点。这样SoundCue就创建完成。如果需要循环播放指定SoundWave,选中后勾选Looping
4,在构造函数中加载该SoundCue
static ConstructorHelpers::FObjectFinder<USoundCue> BattleBMG(TEXT("SoundCue'/Game/Audio/BGM/BattleBMG_SC.BattleBMG_SC'")); USoundCue* SoundBattle = BattleBMG.Object;
5,播放SoundCue。播放SoundCue时,需要指定一个Attach对象,要么是一个Pawn,要么是一个Location;播放SoundWave不需要指定位置,只需要指定场景World即可
UAudioComponent* AC = nullptr; if (SoundBattle) { AC = UGameplayStatics::SpawnSoundAttached(SoundBattle, SelectedHero->GetRootComponent()); }
6,停止播放SoundCue:
UAudioComponent::Stop();
播放SoundWave
1,在构造函数加载SoundWave资源:
static ConstructorHelpers::FObjectFinder<USoundWave> SWBattleBGM(TEXT("SoundWave'/Game/Audio/BGM/BattleBMG.BattleBMG'")); USoundWave* SoundWaveBat = SWBattleBGM.Object;
2,播放SoundWave:
if (SoundWaveBat) { SoundWaveBat->bLooping = true; UGameplayStatics::PlaySound2D(GetWorld(), SoundWaveBat, 0.3f); }
3, 停止播放SoundWave:
FAudioDeviceManager* Manager = GEngine->GetAudioDeviceManager(); if (Manager) { Manager->StopSoundsUsingWave(MySoundWave); }
需要头文件:#include <AudioDeviceManager.h>
注:4.13版本将StopSoundsUsingWave改成了StopSoundsUsingResource