I’m trying to download a song, and then to play it once the download is finished. I don’t want to download the song on my hard drive, but rather to keep it in memory, that’s why when I made TMap<FString, UAudioComponent*> EventAudios
in my AMyActor
class as a private variable. I got this code:
void AMyActor::DownloadSong(const FString& URL, const FString& eventId)
{
TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
HttpRequest->SetVerb(TEXT("GET"));
HttpRequest->SetURL(URL);
HttpRequest->OnProcessRequestComplete().BindLambda([=](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful) {
OnDownloadComplete(Request, Response, bWasSuccessful, eventId);
});
HttpRequest->ProcessRequest();
}
void AMyActor::OnDownloadComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bSuccess, const FString& eventId)
{
if (bSuccess && Response->GetContentLength() > 0)
{
TArray<uint8> DownloadedData = Response->GetContent();
// Create a sound wave object
USoundWave* SoundWave = NewObject<USoundWave>(USoundWave::StaticClass());
// Set the sound wave properties
SoundWave->SoundGroup = ESoundGroup::SOUNDGROUP_Default;
SoundWave->NumChannels = 2; // Assuming 2 channels for AAC audio
SoundWave->Duration = 0.0f; // Set the duration to 0 to indicate it is streaming
// Clear the raw audio data of the sound wave
SoundWave->RawData.RemoveBulkData();
// Set the raw audio data of the sound wave
int32 NumSamples = DownloadedData.Num() / (sizeof(int16) * SoundWave->NumChannels);
SoundWave->RawData.Lock(LOCK_READ_WRITE);
int16* RawDataPtr = (int16*)SoundWave->RawData.Realloc(DownloadedData.Num());
FMemory::Memcpy(RawDataPtr, DownloadedData.GetData(), DownloadedData.Num());
SoundWave->RawData.Unlock();
// Set the sample rate
SoundWave->SetSampleRate(44100); // Set the appropriate sample rate for your audio
// Create an audio component and set its properties
UAudioComponent* AudioComponent = UGameplayStatics::CreateSound2D(this, SoundWave);
AudioComponent->SetVolumeMultiplier(1.0f);
AudioComponent->SetPitchMultiplier(1.0f);
AudioComponent->bAutoDestroy = true;
// Add audio to the map of events
if (EventAudios.Find(eventId))
{
EventAudios[eventId] = AudioComponent;
}
else
{
EventAudios.Emplace(eventId, AudioComponent);
}
// Play the audio
EventAudios[eventId]->Play();
}
However it does not play a sound when I call DownloadSong
. What am I doing wrong?
PS: I am using Unreal Engine 4.25, and I’m trying to play AAC file format.