Example #1
0
        public override void Init()
        {
            filePath = Def.Get <string>("filePath");
            volume   = Def.Get("volume", 1f);
            string format = Def.Get("format", "OGGVORBIS");

            if (!Enum.TryParse <AudioType>(format.Trim(), true, out var formatEnum))
            {
                Core.Error($"Failed to parse audio format '{format}'.");
                Array    arr  = Enum.GetValues(typeof(AudioType));
                object[] args = arr.Cast <object>().ToArray();
                Core.Error($"Valid values are: {string.Join(", ", args)}");
                Core.Error("Note: .mp3 is NOT SUPPORTED. I recommend using .ogg (OGGVORBIS) or .wav (WAV)");
                Remove();
                return;
            }

            // Resolve the file path.
            ModContentPack mcp = Def.modContentPack;

            if (mcp == null)
            {
                string[] split = filePath.Split('/');
                split[0] = split[0].ToLowerInvariant();
                Core.Warn($"Song player program def '{Def.defName}' has been added by a patch operation. Attempting to resolve filepath...");
                var found = LoadedModManager.RunningModsListForReading.FirstOrFallback(mod => mod.PackageId.ToLowerInvariant() == split[0]);
                if (found == null)
                {
                    Core.Error($"Failed to resolve mod folder path from id '{split[0]}'. See below for how to solve this issue.");
                    Core.Error("If you mod's package ID is 'my.mod.name' and your song file is in 'MyModFolder/Songs/Song.mp3' then the correct filePath would be 'my.mod.name/Songs/Song.mp3'");
                    Remove();
                    return;
                }
                Core.Warn("Successfully resolved file path.");
                mcp = found;
            }
            filePath = Path.Combine(mcp.RootDir, filePath);

            if (clipCache.TryGetValue(filePath, out var clip))
            {
                FlagLoadedForClip(clip);
            }
            else
            {
                Task.Run(async() =>
                {
                    try
                    {
                        Core.Log($"Loading '{filePath}' as {formatEnum} ...");
                        var c     = await AudioLoader.TryLoadAsync(filePath, formatEnum);
                        clipToAdd = c; // Push to main thread, see Tick()
                        Core.Log("Done");
                    }
                    catch (Exception e)
                    {
                        Core.Error($"Failed loading song clip from '{filePath}' in format {formatEnum}", e);
                        Remove();
                    }
                });
            }

            string msg = "DSC.NowPlaying".Translate(Def.Get("credits", "Unknown"));

            Messages.Message(msg, MessageTypeDefOf.PositiveEvent);
        }