689 lines
32 KiB
C#
689 lines
32 KiB
C#
using System;
|
||
using System.Linq;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using NAudio.Wave;
|
||
using NAudio.Wave.SampleProviders;
|
||
|
||
namespace GladiatorIdle
|
||
{
|
||
/// <summary>
|
||
/// Ein NAudio-Mixer für alle Sounds: Effekte überlagern sich statt sich gegenseitig
|
||
/// abzuwürgen, Musik läuft auf eigenem Kanal mit Crossfade.
|
||
/// Clips kommen aus Assets/Audio/<name>.mp3 (eingebettet); fehlt einer, spielt der
|
||
/// synthetische Ton von früher. StopAll() bricht sofort alles ab (Game Over / Neustart).
|
||
/// </summary>
|
||
public static class SoundManager
|
||
{
|
||
static bool _enabled = true;
|
||
public static bool Enabled
|
||
{
|
||
get => _enabled;
|
||
set { _enabled = value; if (!value) StopAll(); }
|
||
}
|
||
|
||
/// Lautstärke 0–1 (Einstellungen). Wirkt sofort, auch auf laufende Musik.
|
||
public static float MusicLevel { get; set; } = 1f;
|
||
public static float SfxLevel { get; set; } = 1f;
|
||
public static float VoiceLevel { get; set; } = 1f; // Erzählstimme
|
||
|
||
const int SAMPLE_RATE = 22050; // synthetische Fallback-Töne
|
||
const float MUSIC_VOLUME = 0.55f;
|
||
static readonly WaveFormat MixFormat = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);
|
||
|
||
// ── Synthetische Fallbacks (einmalig beim Start generiert) ───
|
||
static readonly byte[] _wavClick = BuildClick();
|
||
static readonly byte[] _wavTick = BuildTick(1150f);
|
||
static readonly byte[] _wavAmbient = BuildAmbientLoop();
|
||
static readonly byte[] _wavGood = BuildGoodChime();
|
||
static readonly byte[] _wavBad = BuildBadChime();
|
||
static readonly byte[] _wavPurchase = BuildPurchaseBlip();
|
||
static readonly byte[] _wavMilestone = BuildMilestoneMelody();
|
||
static readonly byte[] _wavStart = BuildStartMelody();
|
||
static readonly byte[] _wavAchievement = BuildAchievementFanfare();
|
||
static readonly byte[] _wavLevelUp = BuildLevelUpSound();
|
||
static readonly byte[] _wavDefeat = BuildGameOverMelody();
|
||
static readonly byte[] _wavHit = Note(140f, 0.07f, 0.45f);
|
||
static readonly byte[] _wavBlock = Note(620f, 0.05f, 0.30f);
|
||
static readonly byte[] _wavGong = Note(98f, 1.6f, 0.30f);
|
||
|
||
// ── Öffentliche API ──────────────────────────────────────────
|
||
// Fehlt der Clip in Assets/Audio, spielt der synthetische Ton.
|
||
public static void PlayClick() => Play("sfx_click", _wavClick, cooldownMs: 120);
|
||
public static void PlayTick() => Play("sfx_tick", _wavTick, cooldownMs: 80);
|
||
// Töne, die im Sekundentakt kommen (Training, Schläge, Siege), sind leiser gemischt
|
||
public static void PlayTrain() => Play("sfx_train", _wavTick, cooldownMs: 60, gain: 0.5f); // Trainings-Klick
|
||
public static void PlayCoins() => Play("sfx_coins", _wavPurchase, cooldownMs: 150, gain: 0.6f);
|
||
public static void PlayPurchase() => Play("sfx_purchase", _wavPurchase);
|
||
public static void PlayHit() => Play("sfx_hit", _wavHit, cooldownMs: 60, gain: 0.4f); // Schwerthieb
|
||
public static void PlayBlock() => Play("sfx_block", _wavBlock, cooldownMs: 60, gain: 0.45f); // Schild
|
||
public static void PlayCheer() => Play("sfx_crowd_cheer", _wavGood, cooldownMs: 800, gain: 0.7f);
|
||
public static void PlayBoo() => Play("sfx_crowd_boo", _wavBad, cooldownMs: 800, gain: 0.6f);
|
||
public static void PlayGong() => Play("sfx_gong", _wavGong); // Kampfbeginn
|
||
public static void PlayVictory() => Play("sfx_victory", _wavMilestone);
|
||
public static void PlayDefeat() => Play("sfx_defeat", _wavDefeat);
|
||
public static void PlayLevelUp() => Play("sfx_levelup", _wavLevelUp);
|
||
public static void PlayUnlock() => Play("sfx_unlock", _wavLevelUp);
|
||
public static void PlayAchievement() => Play("sfx_achievement", _wavAchievement);
|
||
public static void PlayStart() => Play("sfx_start", _wavStart);
|
||
public static void PlayTip() => Play("sfx_tip", _wavGood, cooldownMs: 400);
|
||
public static void PlayGoodEvent() => Play("sfx_good", _wavGood); // Probeton (Einstellungen)
|
||
public static void PlayChapterSting() => Play("sting_chapter", _wavMilestone);
|
||
// Duell und Oberfläche (nur mit Datei; fehlt sie, bleibt es still)
|
||
public static void PlaySwing() => Play("sfx_swing", null, cooldownMs: 70, gain: 0.5f);
|
||
public static void PlaySwingHeavy() => Play("sfx_swing_heavy", null, cooldownMs: 120, gain: 0.6f);
|
||
public static void PlayWhoosh() => Play("sfx_whoosh", null, cooldownMs: 120, gain: 0.5f);
|
||
public static void PlayLand() => Play("sfx_land", null, cooldownMs: 200, gain: 0.6f);
|
||
public static void PlayParry() => Play("sfx_parry", null, cooldownMs: 100, gain: 0.6f);
|
||
public static void PlayGuardBreak() => Play("sfx_guardbreak", null, cooldownMs: 150, gain: 0.6f);
|
||
public static void PlayKo() => Play("sfx_ko", null, cooldownMs: 500, gain: 0.7f);
|
||
public static void PlayFury() => Play("sfx_fury", null, cooldownMs: 500, gain: 0.7f);
|
||
public static void PlayFire() => Play("sfx_fire", null, cooldownMs: 90, gain: 0.55f);
|
||
public static void PlayStep() => Play("sfx_step", null, cooldownMs: 160, gain: 0.25f);
|
||
public static void PlayDrawer() => Play("sfx_drawer", null, cooldownMs: 150, gain: 0.45f);
|
||
public static void PlayEquip() => Play("sfx_equip", null, cooldownMs: 120, gain: 0.5f);
|
||
|
||
// ── Erzählstimme (Intro) ─────────────────────────────────────
|
||
// Eigene Spur: immer nur ein Satz gleichzeitig, eigene Lautstärke (VoiceLevel).
|
||
// Solange gesprochen wird, wird die Musik weich leiser ("Ducking").
|
||
|
||
const float DUCK_LEVEL = 0.35f;
|
||
static VoiceClip? _voice;
|
||
static float _duck = 1f;
|
||
|
||
/// Satz aus Assets/Audio/voice_<sprache>_<key>.mp3 vorlesen (Punkte im Key → _).
|
||
/// Dekodiert im Hintergrund (vorher am besten per PreloadVoice), der Aufrufer ruckelt nie.
|
||
/// Vorher und nachher Ruhe: die Stimme wartet, bis laufende Effekte verklungen sind
|
||
/// (höchstens VOICE_WAIT_MAX_MS, danach werden sie ausgeblendet), dann eine kurze Pause;
|
||
/// solange sie spricht und kurz danach startet kein neuer Effekt.
|
||
public static void PlayVoice(string key)
|
||
{
|
||
if (!_enabled || !AppSettings.Narration || VoiceLevel <= 0.001f) return;
|
||
string name = VoiceName(key);
|
||
if (!HasClip(name)) return;
|
||
long ver = Interlocked.Read(ref _sfxVersion);
|
||
long gen = Interlocked.Increment(ref _voiceGen);
|
||
Interlocked.Exchange(ref _voice, null)?.Stop(); // ein früherer Satz endet jetzt
|
||
_voicePending = true; // Musik wird schon in der Pause leiser
|
||
Interlocked.Exchange(ref _quietUntil, long.MaxValue); // ab jetzt keine neuen Effekte
|
||
Task.Run(async () =>
|
||
{
|
||
var data = Clip(name, null);
|
||
// gerade erst angestoßene Effekte sich anmelden lassen (sie dekodieren noch)
|
||
for (int i = 0; i < 20 && Volatile.Read(ref _pendingSfx) > 0; i++) await Task.Delay(20);
|
||
long busy = Interlocked.Read(ref _effectsBusyUntil) - Environment.TickCount64;
|
||
await Task.Delay((int)Math.Clamp(busy, 0, VOICE_WAIT_MAX_MS));
|
||
// langer Nachklang (Kapitel-Gong): weich ausblenden, dann erst die Pause
|
||
bool cutTail = busy > VOICE_WAIT_MAX_MS && Interlocked.Read(ref _voiceGen) == gen;
|
||
if (cutTail) Interlocked.Increment(ref _effectsCut);
|
||
await Task.Delay(VOICE_PRE_MS + (cutTail ? CUT_FADE_MS : 0));
|
||
|
||
var mixer = Mixer;
|
||
bool current = Interlocked.Read(ref _voiceGen) == gen;
|
||
if (data == null || mixer == null || !current || Interlocked.Read(ref _sfxVersion) != ver)
|
||
{
|
||
if (current) { _voicePending = false; Interlocked.Exchange(ref _quietUntil, 0); }
|
||
if (DevShot.SoundLog) DevShot.Log($"sound: voice {key} cancelled");
|
||
return;
|
||
}
|
||
long ms = (long)(data.Length / 2f / MixFormat.SampleRate * 1000);
|
||
Interlocked.Exchange(ref _quietUntil, Environment.TickCount64 + ms + VOICE_POST_MS);
|
||
var v = new VoiceClip(data);
|
||
Interlocked.Exchange(ref _voice, v)?.Stop();
|
||
_voicePending = false;
|
||
mixer.AddMixerInput(v);
|
||
if (DevShot.SoundLog)
|
||
DevShot.Log($"sound: voice {key} {ms} ms (waited for effects {Math.Max(0, busy)} ms{(busy > VOICE_WAIT_MAX_MS ? ", cut" : "")})");
|
||
});
|
||
if (DevShot.SoundLog) DevShot.Log($"sound: voice {key} requested");
|
||
}
|
||
|
||
const int VOICE_PRE_MS = 250, VOICE_POST_MS = 350, VOICE_WAIT_MAX_MS = 1500, CUT_FADE_MS = 300;
|
||
static long _voiceGen, _quietUntil, _effectsBusyUntil;
|
||
static int _pendingSfx;
|
||
static volatile bool _voicePending;
|
||
|
||
/// Wann der zuletzt gestartete Effekt verklingt (für die Ruhe vor der Stimme).
|
||
static void NoteEffectEnd(long endMs)
|
||
{
|
||
long cur;
|
||
do { cur = Interlocked.Read(ref _effectsBusyUntil); if (endMs <= cur) return; }
|
||
while (Interlocked.CompareExchange(ref _effectsBusyUntil, endMs, cur) != cur);
|
||
}
|
||
|
||
/// Sätze schon dekodieren, damit sie auf den Punkt starten.
|
||
public static void PreloadVoice(IEnumerable<string> keys)
|
||
{
|
||
if (!_enabled || !AppSettings.Narration) return;
|
||
var names = keys.Select(VoiceName).Where(HasClip).ToArray();
|
||
Task.Run(() => { foreach (var n in names) Clip(n, null); });
|
||
}
|
||
|
||
// ── Atmosphäre (Geräuschkulisse unter einer Szene) ──────────
|
||
const float AMBIENCE_GAIN = 0.45f;
|
||
static AmbienceVoice? _ambience;
|
||
|
||
/// Geräuschkulisse (Assets/Audio/<name>.mp3) weich ein- und ausgeblendet unter
|
||
/// Musik und Stimme; ersetzt eine laufende weich. Fehlt der Clip: nichts.
|
||
public static void PlayAmbience(string name)
|
||
{
|
||
if (!_enabled || SfxLevel <= 0.001f || !HasClip(name)) return;
|
||
long ver = Interlocked.Read(ref _sfxVersion);
|
||
Task.Run(() =>
|
||
{
|
||
var data = Clip(name, null);
|
||
var mixer = Mixer;
|
||
if (data == null || mixer == null || Interlocked.Read(ref _sfxVersion) != ver) return;
|
||
var a = new AmbienceVoice(data);
|
||
Interlocked.Exchange(ref _ambience, a)?.Stop();
|
||
mixer.AddMixerInput(a);
|
||
});
|
||
}
|
||
|
||
public static void StopAmbience() => Interlocked.Exchange(ref _ambience, null)?.Stop();
|
||
|
||
/// Clips schon dekodieren (Intro), damit sie auf den Punkt starten.
|
||
public static void Preload(IEnumerable<string> names)
|
||
{
|
||
if (!_enabled) return;
|
||
var list = names.Where(HasClip).ToArray();
|
||
Task.Run(() => { foreach (var n in list) Clip(n, null); });
|
||
}
|
||
|
||
/// Clip-Name der Erzählstimme für einen Text-Key in der aktuellen Sprache.
|
||
public static string VoiceName(string key) =>
|
||
$"voice_{L.Current.ToString().ToLowerInvariant()}_{key.Replace('.', '_')}";
|
||
|
||
/// Länge eines Satzes in Sekunden (dekodiert ihn dafür; 0 = fehlt/kaputt). Für Tests.
|
||
public static float VoiceSeconds(string key) =>
|
||
(Clip(VoiceName(key), null)?.Length ?? 0) / 2f / MixFormat.SampleRate;
|
||
|
||
/// Satz abbrechen (auch einen, der noch auf seine Ruhe wartet); Effekte sind sofort wieder frei.
|
||
public static void StopVoice()
|
||
{
|
||
Interlocked.Increment(ref _voiceGen);
|
||
_voicePending = false;
|
||
Interlocked.Exchange(ref _quietUntil, 0);
|
||
Interlocked.Exchange(ref _voice, null)?.Stop();
|
||
}
|
||
|
||
static long _effectsCut;
|
||
|
||
/// Laufende Effekte, Stimme und Geräuschkulisse kurz ausblenden (Musik läuft weiter) und
|
||
/// noch dekodierende verwerfen — vor einer Zwischenszene, damit nichts übereinander liegt.
|
||
public static void CutEffects()
|
||
{
|
||
Interlocked.Increment(ref _effectsCut);
|
||
Interlocked.Increment(ref _sfxVersion);
|
||
Interlocked.Exchange(ref _effectsBusyUntil, Environment.TickCount64 + CUT_FADE_MS);
|
||
StopVoice();
|
||
StopAmbience();
|
||
}
|
||
|
||
/// Länge eines Effekt-Clips in Sekunden (0 = fehlt).
|
||
public static float ClipSeconds(string name) =>
|
||
HasClip(name) ? (Clip(name, null)?.Length ?? 0) / 2f / MixFormat.SampleRate : 0f;
|
||
|
||
/// So lange nach PlayVoice beginnt der Satz frühestens (Ruhe davor), wenn vorher
|
||
/// ein Effekt von <paramref name="effectSeconds"/> Länge gestartet wurde.
|
||
public static float VoiceDelay(float effectSeconds) =>
|
||
Math.Min(effectSeconds, VOICE_WAIT_MAX_MS / 1000f) + VOICE_PRE_MS / 1000f
|
||
+ (effectSeconds * 1000 > VOICE_WAIT_MAX_MS ? CUT_FADE_MS / 1000f : 0f);
|
||
|
||
/// Liest gerade die Erzählstimme? (Musik wird dann gedämpft.)
|
||
static bool VoiceActive => _voicePending || _voice is { Done: false };
|
||
|
||
/// Gibt es den Clip als Datei? (Musik je Lebensphase nur, wenn vorhanden.)
|
||
public static bool HasClip(string name) =>
|
||
typeof(SoundManager).Assembly.GetManifestResourceInfo($"GladiatorIdle.Assets.Audio.{name}.mp3") != null;
|
||
|
||
/// <summary>Hintergrundmusik starten. Ohne Argument: zuletzt gewählter Track.</summary>
|
||
public static void StartAmbient(string? track = null)
|
||
{
|
||
if (track != null) _track = track;
|
||
PlayMusic(_track, loop: true);
|
||
}
|
||
|
||
public static void StopAmbient()
|
||
{
|
||
Interlocked.Increment(ref _musicVersion);
|
||
lock (_musicLock) { _music?.FadeOut(0.8f); _music = null; }
|
||
}
|
||
|
||
/// <summary>Musik-Track mit Crossfade wechseln (Intro: loop = false).</summary>
|
||
public static void PlayMusic(string name, bool loop)
|
||
{
|
||
if (!_enabled) return;
|
||
long ver = Interlocked.Increment(ref _musicVersion);
|
||
byte[]? fallback = name is "music_menu" or "music_ludus" ? _wavAmbient : null;
|
||
Task.Run(() =>
|
||
{
|
||
var data = Clip(name, fallback);
|
||
var mixer = Mixer;
|
||
if (data == null || mixer == null) return;
|
||
lock (_musicLock)
|
||
{
|
||
if (Interlocked.Read(ref _musicVersion) != ver || !_enabled) return;
|
||
if (_music != null && _music.Name == name) return; // läuft schon
|
||
_music?.FadeOut(1.5f);
|
||
_music = new MusicVoice(name, data, loop, MUSIC_VOLUME, fadeInSec: 1.5f);
|
||
mixer.AddMixerInput(_music);
|
||
}
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// Stoppt sofort alle Kanäle und verwirft alle ausstehenden Tasks.
|
||
/// Aufruf bei Game Over und Neustart.
|
||
/// </summary>
|
||
public static void StopAll()
|
||
{
|
||
Interlocked.Increment(ref _musicVersion);
|
||
Interlocked.Increment(ref _sfxVersion);
|
||
Interlocked.Increment(ref _voiceGen); // wartender Satz startet nicht mehr
|
||
_voicePending = false;
|
||
Interlocked.Exchange(ref _quietUntil, 0);
|
||
Interlocked.Exchange(ref _effectsBusyUntil, 0);
|
||
_voice = null;
|
||
_ambience = null;
|
||
lock (_musicLock) _music = null;
|
||
lock (_outLock) _mixer?.RemoveAllMixerInputs();
|
||
}
|
||
|
||
/// <summary>Audio-Ausgabe freigeben (beim Programmende).</summary>
|
||
public static void Shutdown()
|
||
{
|
||
lock (_outLock)
|
||
{
|
||
_out?.Stop();
|
||
_out?.Dispose();
|
||
_out = null;
|
||
_mixer = null;
|
||
}
|
||
}
|
||
|
||
// ── Mixer ────────────────────────────────────────────────────
|
||
|
||
static MixingSampleProvider? _mixer;
|
||
static IWavePlayer? _out;
|
||
static bool _outFailed;
|
||
static readonly object _outLock = new();
|
||
|
||
static MusicVoice? _music;
|
||
static string _track = "music_menu";
|
||
static long _musicVersion;
|
||
static readonly object _musicLock = new();
|
||
|
||
static long _sfxVersion;
|
||
static readonly Dictionary<string, long> _lastPlayed = new();
|
||
static readonly Dictionary<string, float[]?> _clips = new();
|
||
|
||
static MixingSampleProvider? Mixer
|
||
{
|
||
get
|
||
{
|
||
lock (_outLock)
|
||
{
|
||
if (_mixer != null || _outFailed) return _mixer;
|
||
try
|
||
{
|
||
var mixer = new MixingSampleProvider(MixFormat) { ReadFully = true };
|
||
var output = new WaveOutEvent { DesiredLatency = 120 };
|
||
output.Init(mixer);
|
||
output.Play();
|
||
_mixer = mixer;
|
||
_out = output;
|
||
}
|
||
catch { _outFailed = true; } // kein Audiogerät → stumm weiterspielen
|
||
return _mixer;
|
||
}
|
||
}
|
||
}
|
||
|
||
static void Play(string name, byte[]? fallback, long cooldownMs = 0, float gain = 1f)
|
||
{
|
||
if (DevShot.SoundLog) DevShot.Log($"sound: want {name}" + (HasClip(name) || fallback != null ? "" : " (no file)")); // auch stumm prüfbar
|
||
if (!_enabled || SfxLevel <= 0.001f) return;
|
||
if (Environment.TickCount64 < Interlocked.Read(ref _quietUntil)) // Erzählstimme: Ruhe
|
||
{
|
||
if (DevShot.SoundLog) DevShot.Log($"sound: skip {name} (voice quiet)");
|
||
return;
|
||
}
|
||
if (cooldownMs > 0)
|
||
{
|
||
long now = Environment.TickCount64;
|
||
lock (_lastPlayed)
|
||
{
|
||
if (_lastPlayed.TryGetValue(name, out long last) && now - last < cooldownMs) return;
|
||
_lastPlayed[name] = now;
|
||
}
|
||
}
|
||
long ver = Interlocked.Read(ref _sfxVersion);
|
||
Interlocked.Increment(ref _pendingSfx);
|
||
Task.Run(() =>
|
||
{
|
||
try
|
||
{
|
||
var data = Clip(name, fallback);
|
||
var mixer = Mixer;
|
||
if (data == null || mixer == null || Interlocked.Read(ref _sfxVersion) != ver) return;
|
||
long len = (long)(data.Length / 2f / MixFormat.SampleRate * 1000);
|
||
NoteEffectEnd(Environment.TickCount64 + len);
|
||
mixer.AddMixerInput(new ClipVoice(data, gain));
|
||
if (DevShot.SoundLog) DevShot.Log($"sound: sfx {name} {len} ms");
|
||
}
|
||
finally { Interlocked.Decrement(ref _pendingSfx); }
|
||
});
|
||
}
|
||
|
||
/// Fertige Stereo-Daten (44,1 kHz) abspielen – Namensrufe; Lautstärke der Erzählstimme.
|
||
public static void PlayPcm(string name, float[]? data, float gain = 1f)
|
||
{
|
||
if (DevShot.SoundLog) DevShot.Log($"sound: want {name}" + (data == null ? " (not ready)" : ""));
|
||
if (!_enabled || data == null || VoiceLevel <= 0.001f) return;
|
||
var mixer = Mixer;
|
||
if (mixer == null) return;
|
||
mixer.AddMixerInput(new ClipVoice(data, gain * VoiceLevel / Math.Max(0.05f, SfxLevel)));
|
||
}
|
||
|
||
/// Clip dekodiert als 44,1 kHz Stereo-Float, gecacht. MP3 aus Assets/Audio, sonst Fallback-WAV.
|
||
static float[]? Clip(string name, byte[]? fallback)
|
||
{
|
||
lock (_clips)
|
||
if (_clips.TryGetValue(name, out var cached)) return cached;
|
||
|
||
float[]? data = null;
|
||
try
|
||
{
|
||
using var res = typeof(SoundManager).Assembly
|
||
.GetManifestResourceStream($"GladiatorIdle.Assets.Audio.{name}.mp3");
|
||
if (res != null)
|
||
{
|
||
var ms = new MemoryStream();
|
||
res.CopyTo(ms);
|
||
ms.Position = 0;
|
||
using var reader = new Mp3FileReader(ms);
|
||
data = Decode(reader);
|
||
}
|
||
else if (fallback != null)
|
||
{
|
||
using var reader = new WaveFileReader(new MemoryStream(fallback));
|
||
data = Decode(reader);
|
||
}
|
||
}
|
||
catch { data = null; }
|
||
|
||
lock (_clips) _clips[name] = data;
|
||
return data;
|
||
}
|
||
|
||
static float[] Decode(WaveStream reader)
|
||
{
|
||
ISampleProvider sp = reader.ToSampleProvider();
|
||
if (sp.WaveFormat.Channels == 1) sp = new MonoToStereoSampleProvider(sp);
|
||
if (sp.WaveFormat.SampleRate != MixFormat.SampleRate)
|
||
sp = new WdlResamplingSampleProvider(sp, MixFormat.SampleRate);
|
||
|
||
var all = new List<float>();
|
||
var buf = new float[MixFormat.SampleRate * 2];
|
||
int n;
|
||
while ((n = sp.Read(buf, 0, buf.Length)) > 0)
|
||
for (int i = 0; i < n; i++) all.Add(buf[i]);
|
||
return all.ToArray();
|
||
}
|
||
|
||
/// Einmaliger Effekt; liefert 0 am Ende → Mixer entfernt ihn.
|
||
sealed class ClipVoice : ISampleProvider
|
||
{
|
||
readonly float[] _data;
|
||
readonly long _cut = Interlocked.Read(ref _effectsCut);
|
||
int _pos;
|
||
readonly float _gain;
|
||
float _fade = 1f;
|
||
public ClipVoice(float[] data, float gain = 1f) { _data = data; _gain = gain; }
|
||
public WaveFormat WaveFormat => MixFormat;
|
||
|
||
public int Read(float[] buffer, int offset, int count)
|
||
{
|
||
int n = Math.Min(count, _data.Length - _pos);
|
||
bool cut = Interlocked.Read(ref _effectsCut) != _cut;
|
||
if (n <= 0 || (cut && _fade <= 0)) return 0;
|
||
float lv = SfxLevel * _gain;
|
||
for (int i = 0; i < n; i++)
|
||
{
|
||
if (cut) _fade = Math.Max(0, _fade - 1f / (MixFormat.SampleRate * 2 * CUT_FADE_MS / 1000f)); // weich ausblenden
|
||
buffer[offset + i] = _data[_pos + i] * lv * _fade;
|
||
}
|
||
_pos += n;
|
||
return n;
|
||
}
|
||
}
|
||
|
||
/// Satz der Erzählstimme; kann vorzeitig (weich) beendet werden.
|
||
sealed class VoiceClip : ISampleProvider
|
||
{
|
||
readonly float[] _data;
|
||
int _pos;
|
||
volatile bool _stop;
|
||
float _fade = 1f;
|
||
public VoiceClip(float[] data) => _data = data;
|
||
public WaveFormat WaveFormat => MixFormat;
|
||
public bool Done => _stop || _pos >= _data.Length;
|
||
public void Stop() => _stop = true;
|
||
|
||
public int Read(float[] buffer, int offset, int count)
|
||
{
|
||
int n = Math.Min(count, _data.Length - _pos);
|
||
if (n <= 0 || (_stop && _fade <= 0)) return 0;
|
||
float lv = VoiceLevel;
|
||
for (int i = 0; i < n; i++)
|
||
{
|
||
if (_stop) _fade = Math.Max(0, _fade - 1f / 4410f); // 50 ms ausblenden
|
||
buffer[offset + i] = _data[_pos + i] * lv * _fade;
|
||
}
|
||
_pos += n;
|
||
return n;
|
||
}
|
||
}
|
||
|
||
/// Geräuschkulisse: 0,6 s einblenden, zum Clip-Ende (oder bei Stop) 0,8 s ausblenden.
|
||
sealed class AmbienceVoice : ISampleProvider
|
||
{
|
||
const int FADE_IN = 44100 * 2 * 6 / 10, FADE_OUT = 44100 * 2 * 8 / 10; // Samples (Stereo)
|
||
readonly float[] _data;
|
||
int _pos, _stopAt = int.MaxValue;
|
||
public AmbienceVoice(float[] data) => _data = data;
|
||
public WaveFormat WaveFormat => MixFormat;
|
||
public void Stop() => _stopAt = Math.Min(_stopAt, _pos);
|
||
|
||
public int Read(float[] buffer, int offset, int count)
|
||
{
|
||
int end = Math.Min(_data.Length, _stopAt == int.MaxValue ? _data.Length : _stopAt + FADE_OUT);
|
||
int n = Math.Min(count, end - _pos);
|
||
if (n <= 0) return 0;
|
||
float lv = SfxLevel * AMBIENCE_GAIN;
|
||
for (int i = 0; i < n; i++)
|
||
{
|
||
int p = _pos + i;
|
||
float env = Math.Min(1f, p / (float)FADE_IN);
|
||
env = Math.Min(env, (end - p) / (float)FADE_OUT);
|
||
buffer[offset + i] = _data[p] * lv * Math.Max(0f, env);
|
||
}
|
||
_pos += n;
|
||
return n;
|
||
}
|
||
}
|
||
|
||
/// Musik mit Loop und Lautstärke-Rampe (Ein-/Ausblenden, Crossfade).
|
||
sealed class MusicVoice : ISampleProvider
|
||
{
|
||
readonly float[] _data;
|
||
readonly bool _loop;
|
||
int _pos;
|
||
float _vol, _target, _step;
|
||
volatile bool _fadingOut;
|
||
|
||
public string Name { get; }
|
||
public WaveFormat WaveFormat => MixFormat;
|
||
|
||
public MusicVoice(string name, float[] data, bool loop, float volume, float fadeInSec)
|
||
{
|
||
Name = name; _data = data; _loop = loop; _target = volume;
|
||
_step = volume / Math.Max(1f, fadeInSec * MixFormat.SampleRate);
|
||
}
|
||
|
||
public void FadeOut(float sec)
|
||
{
|
||
_step = Math.Max(_vol, 0.001f) / Math.Max(1f, sec * MixFormat.SampleRate);
|
||
_target = 0;
|
||
_fadingOut = true;
|
||
}
|
||
|
||
public int Read(float[] buffer, int offset, int count)
|
||
{
|
||
if (_fadingOut && _vol <= 0) return 0;
|
||
for (int i = 0; i < count; i += 2)
|
||
{
|
||
if (_pos >= _data.Length)
|
||
{
|
||
if (!_loop)
|
||
{
|
||
if (i == 0) return 0;
|
||
Array.Clear(buffer, offset + i, count - i);
|
||
return count;
|
||
}
|
||
_pos = 0;
|
||
}
|
||
_vol = _vol < _target ? Math.Min(_target, _vol + _step) : Math.Max(_target, _vol - _step);
|
||
// Ducking: ~0,3 s leiser werden, ~0,8 s zurück
|
||
float duckTarget = VoiceActive ? DUCK_LEVEL : 1f;
|
||
_duck = _duck > duckTarget ? Math.Max(duckTarget, _duck - 1f / 13000f)
|
||
: Math.Min(duckTarget, _duck + 1f / 35000f);
|
||
float v = _vol * MusicLevel * _duck;
|
||
buffer[offset + i] = _data[_pos] * v;
|
||
buffer[offset + i + 1] = _data[_pos + 1] * v;
|
||
_pos += 2;
|
||
}
|
||
return count;
|
||
}
|
||
}
|
||
|
||
// ── Melodie-Generatoren (Fallback) ───────────────────────────
|
||
|
||
static byte[] BuildStartMelody() => Sequence(
|
||
Note(261.6f, 0.12f), Note(329.6f, 0.12f),
|
||
Note(392.0f, 0.12f), Note(523.3f, 0.25f));
|
||
|
||
static byte[] BuildMilestoneMelody() => Sequence(
|
||
Note(659.3f, 0.10f), Note(783.9f, 0.10f), Note(1046.5f, 0.25f));
|
||
|
||
static byte[] BuildGoodChime() => Sequence(
|
||
Note(523.3f, 0.08f), Note(659.3f, 0.18f));
|
||
|
||
static byte[] BuildBadChime() => Sequence(
|
||
Note(330.0f, 0.10f), Note(220.0f, 0.22f));
|
||
|
||
static byte[] BuildPurchaseBlip() => Sequence(
|
||
Note(880.0f, 0.06f), Note(1108.7f, 0.10f));
|
||
|
||
static byte[] BuildGameOverMelody() => Sequence(
|
||
Note(392.0f, 0.18f), Note(329.6f, 0.18f),
|
||
Note(261.6f, 0.18f), Note(220.0f, 0.40f));
|
||
|
||
static byte[] BuildTick(float freq) => Sequence(Note(freq, 0.04f, 0.05f));
|
||
|
||
static byte[] BuildAchievementFanfare() => Sequence(
|
||
Note(523.3f, 0.07f, 0.30f), Note(659.3f, 0.07f, 0.30f),
|
||
Note(783.9f, 0.07f, 0.30f), Note(1046.5f, 0.14f, 0.35f),
|
||
Note(1318.5f, 0.28f, 0.30f));
|
||
|
||
|
||
static byte[] BuildLevelUpSound() => Sequence(
|
||
Note(392.0f, 0.08f, 0.28f), Note(523.3f, 0.08f, 0.28f),
|
||
Note(659.3f, 0.08f, 0.28f), Note(784.0f, 0.24f, 0.32f));
|
||
|
||
static byte[] BuildClick() => Sequence(Note(900.0f, 0.03f, 0.12f));
|
||
|
||
|
||
static byte[] BuildAmbientLoop()
|
||
{
|
||
// 8-sekündiger weicher Ambient-Pad (A-Moll Klang, sehr leise)
|
||
int total = SAMPLE_RATE * 8;
|
||
int fadeLen = SAMPLE_RATE * 2;
|
||
float[] freqs = { 110f, 146.8f, 165f, 220f, 261.6f };
|
||
float[] vols = { 0.08f, 0.06f, 0.05f, 0.06f, 0.04f };
|
||
var samples = new short[total];
|
||
for (int i = 0; i < total; i++)
|
||
{
|
||
double t = (double)i / SAMPLE_RATE;
|
||
double wave = 0;
|
||
for (int k = 0; k < freqs.Length; k++)
|
||
wave += Math.Sin(2 * Math.PI * freqs[k] * t) * vols[k];
|
||
double env = 1.0;
|
||
if (i < fadeLen) env = (double)i / fadeLen;
|
||
if (i > total - fadeLen) env = (double)(total - i) / fadeLen;
|
||
samples[i] = (short)(wave * env * 32767 * 0.35);
|
||
}
|
||
return SamplesToWav(samples);
|
||
}
|
||
|
||
|
||
// ── PCM-Generierung ──────────────────────────────────────────
|
||
|
||
static short[] GenerateSamples(float freq, float durationSec, float volume = 0.35f)
|
||
{
|
||
int total = (int)(SAMPLE_RATE * durationSec);
|
||
int fadeLen = Math.Min(total / 8, 400);
|
||
var samples = new short[total];
|
||
for (int i = 0; i < total; i++)
|
||
{
|
||
double t = (double)i / SAMPLE_RATE;
|
||
double wave = Math.Sin(2 * Math.PI * freq * t);
|
||
double env = 1.0;
|
||
if (i < fadeLen) env = (double)i / fadeLen;
|
||
if (i > total - fadeLen) env = (double)(total - i) / fadeLen;
|
||
samples[i] = (short)(wave * env * volume * 32767);
|
||
}
|
||
return samples;
|
||
}
|
||
|
||
static byte[] Note(float freq, float duration, float volume = 0.35f)
|
||
=> SamplesToWav(GenerateSamples(freq, duration, volume));
|
||
|
||
static byte[] Sequence(params byte[][] notes)
|
||
{
|
||
using var ms = new MemoryStream();
|
||
foreach (var wav in notes) ms.Write(wav, 44, wav.Length - 44);
|
||
return SamplesToWav(BytesToShorts(ms.ToArray()));
|
||
}
|
||
|
||
static byte[] SamplesToWav(short[] samples)
|
||
{
|
||
const int ch = 1, bps = 16;
|
||
int byteRate = SAMPLE_RATE * ch * bps / 8;
|
||
int align = ch * bps / 8;
|
||
int dataSize = samples.Length * align;
|
||
using var ms = new MemoryStream(44 + dataSize);
|
||
using var bw = new BinaryWriter(ms);
|
||
bw.Write(new[]{'R','I','F','F'}); bw.Write(36 + dataSize);
|
||
bw.Write(new[]{'W','A','V','E'});
|
||
bw.Write(new[]{'f','m','t',' '}); bw.Write(16);
|
||
bw.Write((short)1); bw.Write((short)ch);
|
||
bw.Write(SAMPLE_RATE); bw.Write(byteRate);
|
||
bw.Write((short)align); bw.Write((short)bps);
|
||
bw.Write(new[]{'d','a','t','a'}); bw.Write(dataSize);
|
||
foreach (short s in samples) bw.Write(s);
|
||
return ms.ToArray();
|
||
}
|
||
|
||
static short[] BytesToShorts(byte[] bytes)
|
||
{
|
||
var s = new short[bytes.Length / 2];
|
||
for (int i = 0; i < s.Length; i++) s[i] = BitConverter.ToInt16(bytes, i * 2);
|
||
return s;
|
||
}
|
||
}
|
||
}
|