MZ (WIP) Palette Audio ala Skyrim - BotW (not as sophisticated)

I know, I know, yet another audio attempt by me... but what can I say? Except "Help", of course, as I'm currently swamped and have no idea how to make it work.

JavaScript:
/*:
 * @plugindesc BGM Palette Plugin - Play a palette of audio files as map BGM in random or sequential order using notetags
 * @target MZ
 * @url TBC
 * @author Dark_Ansem
 *
 * @help
 * To use this plugin, add the following notetag in the map's "Note" field:
 * <BGM_Palette: folder_name, file1, file2, file3, ..., mode>
 *   - folder_name: The folder within audio/bgm where your palette audio files are located.
 *   - file1, file2, file3, ...: A comma-separated list of audio file names without file extensions.
 *   - mode: The playback mode for audio files: 'random' or 'sequential'.
 */

(() => {
  const pluginName = "BGM_Palette";

  let currentIndex = 0;
  let audioFolder = '';
  let audioFiles = [];
  let playbackMode = '';

  const playNext = () => {
    let nextIndex;
    if (playbackMode === "random") {
      nextIndex = Math.floor(Math.random() * audioFiles.length);
    } else {
      nextIndex = (currentIndex + 1) % audioFiles.length;
    }

    const audioFile = {
      name: `${audioFolder}/${audioFiles[nextIndex]}`,
      volume: 100,
      pitch: 100,
      pan: 0,
    };

    AudioManager.playBgm(audioFile);
    currentIndex = nextIndex;
  };

  const _Scene_Map_update = Scene_Map.prototype.update;
  Scene_Map.prototype.update = function() {
    _Scene_Map_update.call(this);

    if (audioFiles.length > 0 && AudioManager._bgmBuffer && AudioManager._bgmBuffer.isPlaying() && AudioManager._bgmBuffer._audioNode && AudioManager._bgmBuffer._audioNode.ended) {
      playNext();
    }
  };

  const _Game_Map_setup = Game_Map.prototype.setup;
  Game_Map.prototype.setup = function (mapId) {
    _Game_Map_setup.call(this, mapId);
    this.setupBgmPalette();
  };

  Game_Map.prototype.setupBgmPalette = function () {
    const mapNote = $dataMap.note;
    const notetagRegex = /<BGM_Palette:\s*([^,]+)((?:,\s*[^,]+)+),\s*(random|sequential)\s*>/i;

    if (mapNote.match(notetagRegex)) {
      audioFolder = RegExp.$1.trim();
      audioFiles = RegExp.$2.trim().split(',').map(file => file.trim()).filter(file => file);
      playbackMode = RegExp.$3.trim();

      playNext();
    } else {
      // Stop BGM when leaving the map with the BGM_Palette notetag
      AudioManager.stopBgm();
      audioFiles = [];
    }
  };
})();

EDIT: it's broken... let me fix it.
EDIT nth: good lord, this is a nightmare!
EDIT nNth: ok so, I am at my wit's end and have no idea how to make it work the way it is meant to. It doesn't crash, but it doesn't work properly either.
Did you write this? Just taking a quick scan through, there's some odd things.

What's the point of the audioFolder variable? It's set to nothing and it doesn't look like there's a plugin parameter or anything to ever give it a value, so it's just doing nothing.

Then, when you create the name of the audio files, you're including the directory slash in there regardless of whether anything is in the audioFolder variable. But playBgm already includes a slash in its code, so I suspect you'll never get a valid filepath to load anything.

As this is for MZ, your if statement in Scene_Map.update() is hugely over-complicated. See the optional chaining operator:

In setupBgmPalette(), why do you stop the background music if the map doesn't have any notetags? The condition for that else branch doesn't have anything to do with your comment about the player leaving the map.
Did you write this? Just taking a quick scan through, there's some odd things.
Unsurprisingly, as I made it - and was also distracted by Barubary.
What's the point of the audioFolder variable? It's set to nothing and it doesn't look like there's a plugin parameter or anything to ever give it a value, so it's just doing nothing.
It's supposed to be used for the notetag to tell it where to look for the files, ideally I wanted to just rely on folder name but apparently RPG Maker MZ can't work like that. so, was it wrong?
Then, when you create the name of the audio files, you're including the directory slash in there regardless of whether anything is in the audioFolder variable. But playBgm already includes a slash in its code, so I suspect you'll never get a valid filepath to load anything.
The files load, but obviously incorrectly as only one gets played - but it changes every time the map is re-entered.

In setupBgmPalette(), why do you stop the background music if the map doesn't have any notetags? The condition for that else branch doesn't have anything to do with your comment about the player leaving the map.
To prevent the audio from seeping into other maps - like the other, much easier plugin I released, where the changes made in one map weren't reverted. It's not necessary?
It's supposed to be used for the notetag to tell it where to look for the files, ideally I wanted to just rely on folder name but apparently RPG Maker MZ can't work like that. so, was it wrong?
I'm not sure I understand what you're saying. The playBgm() function takes a specific file name. i.e. if you were trying to play "talking.ogg," it would expect the object you pass to the function to have name: "talking"

To prevent the audio from seeping into other maps - like the other, much easier plugin I released, where the changes made in one map weren't reverted. It's not necessary?
I see what you're going for.
I'm not sure I understand what you're saying. The playBgm() function takes a specific file name. i.e. if you were trying to play "talking.ogg," it would expect the object you pass to the function to have name: "talking"
so it can't look by itself in a specific folder?
so it can't look by itself in a specific folder?
I'm not trying to be overly punctilious, but sometimes you use wording that makes me unsure what things you understand or don't.

A computer doesn't do anything by itself, right? 😉 You can have your code do whatever you want, but you have to format it correctly.

If you look at the code of the playBgm() function you're calling, you will see it starts in your project directory and applies the folder path "bgm/" followed by the filename you supply (I mentioned this above, did you look at it already?).

Therefore, if you pass in an object to playBgm() that has the name property "/talking" (which is what you get if you look at the first line after "const audioFile"), you will end up with a complete path of "bgm//talking" which is incorrect syntax.

Now that may or may not be causing you an error, but it's an example of unintended outcomes.

Another example is a few lines down, you have a comma after "pan: 0" - having a comma there is telling the engine to expect more members in that object, but there aren't any. Again, this may or may not be throwing an error in your code, but it's something you need to be more careful about.

So it took until post 3 to actually say - exactly what is the problem you're experiencing? One BGM plays and then nothing else?

What have you tried for troubleshooting? Have you put a console.log() inside playNext() to see if it's ever getting called after that behemoth of a conditional?
I'm not trying to be overly punctilious, but sometimes you use wording that makes me unsure what things you understand or don't.
Your police attitude is, believe it or not, one of the reasons I appreciate you, even if sometimes it would be nice to have a gentler attitude, wording or not.
Your default option should be "I don't understand this".
So it took until post 3 to actually say - exactly what is the problem you're experiencing? One BGM plays and then nothing else?
I said it in literally my first reply to you?
What have you tried for troubleshooting? Have you put a console.log() inside playNext() to see if it's ever getting called after that behemoth of a conditional?
I'm using it in the VS sample game in order to iron out the massive mistakes, but no, didn't do that yet (because yes, in its first iteration it literally crashed the game).
If you look at the code of the playBgm() function you're calling, you will see it starts in your project directory and applies the folder path "bgm/" followed by the filename you supply (I mentioned this above, did you look at it already?).
No, I've just come back home.

At any rate, making the "if" simpler led me to "TypeError Cannot read property 'ended' of undefined" so now, took care of that.

so now I'm back at start, with 5 extra lines of code and still the problem that it only randomizes the selected audio when entering the map, but it incapable of playing multiple audio files in the same map.
I said it in literally my first reply to you?
Correct - if you look on the upper right, that's post #3 😉 I was just saying that your original post didn't have a clear description of what the actual problem was, just "it doesn't work properly."

so now I'm back at start, with 5 extra lines of code and still the problem that it only randomizes the selected audio when entering the map, but it incapable of playing multiple audio files in the same map.
So the logical step is to see whether playNext() is ever getting called. Put a console.log() line in there and see if anything pops up when your current music ends. (and/or put an else branch in Scene_Map.update() with a console.log() saying "playNext not called").

That will tell you whether it's an error in that function or an error in the condition for calling the function.
Correct - if you look on the upper right, that's post #3 😉 I was just saying that your original post didn't have a clear description of what the actual problem was, just "it doesn't work properly."
Of course, like a cat.
So the logical step is to see whether playNext() is ever getting called. Put a console.log() line in there and see if anything pops up when your current music ends. (and/or put an else branch in Scene_Map.update() with a console.log() saying "playNext not called").
so yes, this is the message that appeared: 525 paletteaudio.js:56 playNext not called
Okay, so that's telling you that your conditional to call playNext() is failing. You'll need to paste how it currently reads.
This is the reasoning that I applied

JavaScript:
(() => {
  // Declare plugin variables
  const pluginName = "BGM_Palette";
  let currentIndex = 0;
  let audioFolder = '';
  let audioFiles = [];
  let playbackMode = '';

  // Define the playNext function, which plays the next BGM in the list
  const playNext = () => {
    let nextIndex;
    // Determine the index of the next BGM based on the playback mode
    if (playbackMode === "random") {
      nextIndex = Math.floor(Math.random() * audioFiles.length);
    } else {
      nextIndex = (currentIndex + 1) % audioFiles.length;
    }

    // Define the audioFile object with the proper file path, volume, pitch, and pan
    const audioFile = {
      name: `${audioFolder}/${audioFiles[nextIndex]}`,
      volume: 100,
      pitch: 100,
      pan: 0
    };

    // Log the audioFile and play the BGM
    console.log('playNext called:', audioFile);
    AudioManager.playBgm(audioFile);
    currentIndex = nextIndex;
  };

  // Override the Scene_Map.prototype.update function to play the next BGM when the current one ends
  const _Scene_Map_update = Scene_Map.prototype.update;
  Scene_Map.prototype.update = function() {
    _Scene_Map_update.call(this);

    if (
      audioFiles.length > 0 &&
      AudioManager._bgmBuffer &&
      AudioManager._bgmBuffer._audioNode &&
      AudioManager._bgmBuffer._audioNode.ended
    ) {
      playNext();
    } else {
      console.log('playNext not called');
    }
  };

  // Override the Game_Map.prototype.setup function to set up the BGM palette when entering a map
  const _Game_Map_setup = Game_Map.prototype.setup;
  Game_Map.prototype.setup = function (mapId) {
    _Game_Map_setup.call(this, mapId);
    this.setupBgmPalette();
  };

  // Define the Game_Map.prototype.setupBgmPalette function to configure the BGM palette based on the map's notetag
  Game_Map.prototype.setupBgmPalette = function () {
    const mapNote = $dataMap.note;
    const notetagRegex = /<BGM_Palette:\s*([^,]+)((?:,\s*[^,]+)+),\s*(random|sequential)\s*>/i;

    // Check if the map has a valid BGM_Palette notetag, and if so, set up the BGM palette
    if (mapNote.match(notetagRegex)) {
      audioFolder = RegExp.$1.trim();
      audioFiles = RegExp.$2.trim().split(',').map(file => file.trim()).filter(file => file);
      playbackMode = RegExp.$3.trim();

      playNext();
    } else {
      // Stop BGM when leaving the map with the BGM_Palette notetag
      AudioManager.stopBgm();
      audioFiles = [];
    }
  };
})();
That's still overly complicated - my first reply mentioned to you the optional chaining operator. Your condition could simply be:
Code:
if (audioFiles.length>0 && AudioManager._bgmBuffer?._audioNode?.ended)

Making it more efficient aside, it seems you simply need to see which part of that condition is failing. Have you added a console.log() that prints out the current value of those things?

What other plugins are you using? That audioNode stuff you're referencing doesn't exist in MZ.
That audioNode stuff you're referencing doesn't exist in MZ.
I'm using the VS plugin, I thought audionode was present in their suite? I might have got mixed up, still drunk on my success of my other release. Let me try to fix it, but I need a cup of tea. or a cappuccino. Or something.
I can't tell you anything about VisuStella plugins. If you're making your plugin dependent on something they wrote,
- that's important to say up front

- you'll have to wait for someone else to look it over.

And continue to follow basic troubleshooting methods as I described above.
I deleted the reference to that since it didn't make a difference anyway.

With the extra console checks, I got this:

playNext not called: 3 WebAudio {_isPlaying: true, _loadListeners: Array(0), _data: null, _fetchedSize: 0, _fetchedData: Array(0), …} true
Then it seems to me your code is going to try to start a new BGM track every time the map update function is called.

The length of the audioFiles array will be greater than 0 because you defined it in your notetag. And bgmBuffer will always have a value if any BGM is currently playing. So if you removed the stuff to undefined audioNode, I would expect that if statement is always evaluating to true and you'd be constantly restarting music.

Is that not what you're seeing in your log?
This is what I'm seeing now after some extra tinkering (Thank you Notepad++)

playNext not called: 3 WebAudio {_isPlaying: true, _loadListeners: Array(0), _data: null, _fetchedSize: 0, _fetchedData: Array(0), …} true
I could always rely on a different solution, takes up more HDD space but it's nowhere as irritating...
ok, so I decided to try a different approach, have a different BGM play depending on the value of a variable. And in a way it works, but I got stuck in this loop:

JavaScript:
function checkVariableBgmChange() {
    try {
        const mapNotes = $dataMap.note;
        const variableNoteRegex = /<BGMChangeVariable: ((\d+, \d+, \w+,?)+)>/g;
        let variableMatch;
        while (variableMatch = variableNoteRegex.exec(mapNotes)) {
            const variables = variableMatch[1].split(', ');
            const variableCount = variables.length / 3;
            for (let i = 0; i < variableCount; i++) {
                const variableId = Number(variables[i * 3]);
                const variableValue = Number(variables[i * 3 + 1]);
                const bgmName = variables[i * 3 + 2];
                if ($gameVariables.value(variableId) >= variableValue) {
                    console.log(`Variable ${variableId} is now ${$gameVariables.value(variableId)}, changing BGM to ${bgmName}`);
                    $gameMap.autoplay();
                    AudioManager.playBgm({ name: bgmName, pan: 0, pitch: 100, volume: 100 });
                    return;
                }
            }
        }
    } catch (error) {
        console.error('Error in BGM Change Plugin (Variable):', error);
    }
}

The console log says the following
Variable 28 is now 0, changing BGM to Dungeon1
Variable 28 set to 1
Variable 28 is now 1, changing BGM to Dungeon1
Variable 28 set to 2
Variable 28 is now 2, changing BGM to Dungeon1

the error, apparently, is that whenever the variable changes, it DOES change the music, but it incorrectly only to Dungeon1 as specified in the notetag <BGMChangeVariable: 28, 0, Dungeon1, 1, Dungeon2, 2, Dungeon3> but I'm banging against the wall on how to fix it. Help much appreciated.
Please close the thread, I found an alternative solution,

Original thread: https://forums.rpgmakerweb.com/threads/wip-palette-audio-ala-skyrim-botw-not-as-sophisticated.157315/