Search code examples
c++audiounreal-engine4

UE4 Playback time in C++


I'm working on Sound Handling lately, but I've encountered big problem. What I want to achieve, is to get Playback Time(how long sound has been played till now for example i have 10 sec sound and i pasue it after 3 seconds so i should get value of 7 back). This is my current function:

float MyAudioClass::GetPlaybackTime(UAudioComponent* AComponent, float &PlaybackTime)
{
    if (AComponent)
    {
        FAudioDevice* AudioDevice = AComponent->GetAudioDevice();
        if (AudioDevice)
        {
            FActiveSound* ActiveSound = AudioDevice->FindActiveSound(AComponent->GetAudioComponentID());
            if (ActiveSound)
            {
                PlaybackTime = ActiveSound->PlaybackTime;
                return PlaybackTime;
            }
            return 0;
        }
        return 0;
    }
    return 0;
}

However when I'm trying to use it, whole engine crashes and I recieve this error:

Assertion failed: IsInAudioThread()
myaudioclass.cpp:173
myaudioclass.h:41

Error lines are in order:

if (ActiveSound) //173
    GENERATED_BODY() //41

What Am I doing wrong here? If someone is that kind to help me i would really appreciate that :3


Solution

  • As Graeme said, you have to run the code in the audio thread.

    Here is a snippet used in AudioComponent.cpp:

    if (FAudioDevice* AudioDevice = GetAudioDevice())
    {
        const uint64 MyAudioComponentID = AudioComponentID;
        FAudioThread::RunCommandOnAudioThread([AudioDevice, MyAudioComponentID, InName, InFloat]()
        {
            FActiveSound* ActiveSound = AudioDevice->FindActiveSound(MyAudioComponentID);
            if (ActiveSound)
            {
                ActiveSound->SetFloatParameter(InName, InFloat);
            }
        }, GET_STATID(STAT_AudioSetFloatParameter));
    }