0

I have a really weird bug that I cannot fix. I have an introduction where the user sees an image and an audio is played. Then when the user presses forward it goes to the next image+audio.

On each view I have play, pause and replay buttons. On the first screen it works everything as it should, on the second screen (the screen is the same, only new files are loaded) pressing playing after pausing will restart the audio from the beginning instead of playing from when it was paused.

Here the code:

public void PlayAudio()
{
    if (_bIsAudioPaused)
    {
        _audioSource.UnPause();
    }
    else
    {
        _audioSource.Play();
    }

    _playButton.SetActive(false);
    _bIsAudioPaused = false;
    _bIsAudioPlaying = true;
    Screen.sleepTimeout = SleepTimeout.NeverSleep;
}

public void PauseAudio()
{
    _audioSource.Pause();
    _bIsAudioPaused = true;
    _bIsAudioPlaying = false;
    Screen.sleepTimeout = SleepTimeout.SystemSetting;
}

public void ReplayAudio()
{
    PlayAudio();
}

public void AudioFinished()
{
    _bIsAudioPlaying = false;
    Screen.sleepTimeout = SleepTimeout.SystemSetting;
}
private void Update()
{
    if (_bIsAudioPlaying && !_audioSource.isPlaying)
    {
        AudioFinished();
    }
}

If I debug the code on the visual studio, at the moment that it goes to the line _audioSource.UnPause() I can hear the audio restarting as it should. But then when I finish debugging and go back to unity, it will restart the audio from the beginning.

I have tried to set AudioSource's play on awake to false, but it doens't help.

hijinxbassist
  • 3,667
  • 1
  • 18
  • 23
Vanessa M
  • 21
  • 3
  • After going to the second scene, if I can back to the scene before, the probleme will occur on the first scene as well. I was loading the clip without stopping the audio source before, so corrected that bit, but still couldn't solve the bug. – Vanessa M Jun 17 '23 at 19:53

1 Answers1

0

There isn't enough information for me to pinpoint the issue. I recommend using an audio manager with a singleton design pattern. This will make debugging much easier.

A singleton design just means that there will only ever be one instance of that class. So in your case, you'll have one audio class and all of your other classes will be referring to that one single instance.

Here is how to implement the singleton design pattern: https://awesometuts.com/blog/singletons-unity/

This is SUDO-CODE for the Audio Manager

//public class AudioManager {
    // public audioClipVariable[]
    // private audioIndex = 0;

    /* IMPLEMENT SINGLETON DESIGN PATTERN */

    // public NextAudio(){
        // StopAudio();
        // audioIndex++;
        // PlayAudio();
    // }
    
    // public StopAudio(){
        // audioClipVariable[audioIndex].stop();
    // }

    // public PlayAudio{
        // audioClipVariable[audioIndex].play();
    // }

    // public PauseAudio{
        // audioClipVariable[audioIndex].pause();
    // }
//}