Changing rooms without the music starting over.

Started by lizardwizard, Tue 27/12/2022 23:41:19

Previous topic - Next topic

lizardwizard

I want two rooms to have the same music, but when I change from one to the other I want the music to keep playing without it starting over. Can it be done?

newwaveburritos

It can certainly be done.  Where and how do you start the music playing?  How do you have the audio/music in your project?

lizardwizard

I start the music upon entering the room. In the audio tab there's a music folder, and the tutorial that I watched said to name the files "aMusic1" and so on.

// room script file

function room_AfterFadeIn()
{
 aMusic1.Play();
}

Crimson Wizard

#3
There are two approaches to this.

SOLUTION 1. Keeping track of what music you are playing

If you have only 1 channel reserved for the music (this may be checked in the Editor: Audio -> Types -> Music -> MaxChannels).
Make a global variable of AudioChannel* type, and save returned value from Play() function. Next time you need to play a music, test this variable and see if same music is played on that channel.
Name that variable "MusicChannel", for example.
The global variable may be created in "Global Variables" panel, or by hand in script if you know how to do that.

Every time you play a music, any music, you must remember to assign Play's return value into that variable:
Code: ags
MusicChannel = aSomeMusic.Play();

And for each case where you want to prevent same music restart, use this code:
Code: ags
function room_AfterFadeIn()
{
    // This means that you will start music IF:
    // * the channel variable was not initialized yet (this means no music played before), OR
    // * the currently playing clip is NOT this music
    if ((MusicChannel == null) || (MusicChannel.PlayingClip != aMusic1))
    {
        MusicChannel = aMusic1.Play();
    }
}



SOLUTION 2. Test each channel to see if your music is playing

All audio channels can be accessed using System.AudioChannels[] array, and their total number is in System.AudioChannelCount. This means that you may iterate through all of them and find out what is playing on them at any given time.

For convenience, make a custom function in GlobalScript:
Code: ags
bool IsAudioClipPlaying(AudioClip* clip)
{
    for (int i = 0; i < System.AudioChannelCount; i++)
    {
        if (System.AudioChannels[i].PlayingClip == clip)
        {
            return true; // found it
        }
    }
    return false; // nowhere
}

Declare this function in GlobalScript's header, this will let you use it in any room:
Code: ags
import bool IsAudioClipPlaying(AudioClip* clip);

And now you can do this in your rooms:
Code: ags
function room_AfterFadeIn()
{
     // '!' sign means logical NOT, so this means "if NOT playing"
    if (!IsAudioClipPlaying(aMusic1))
    {
        aMusic1.Play();
    }
}


SMF spam blocked by CleanTalk