Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ and a release's notes are its section. The procedure is in [`docs/RELEASING.md`]
the line. The client sizes it, not the world: F7 ▸ Links & pictures ▸ **pictures in a line, tallest (rows)** sets how
tall (2 by default), and 0 puts such pictures under their line as before. A picture on a line of its own, or in a
box the world laid out, is drawn as it was.
- A trigger can play a sound when it matches: F2 ▸ **sound** takes the full path to a .wav, .mp3, .ogg or .flac file
on your computer, and in the window **Choose…** picks one and **Play** tries it. It plays at F7's master and sound
levels even when the line is gagged, stays on when F7's **game sound** (the world's own sounds) is off, and is
silenced by Ctrl+P ▸ Mute sound. A rule that matches again while its sound is playing starts it over. Rules with a
sound show ♪ in F2's list, and a MUSHclient import keeps a trigger's sound when the file is on this computer.
- The client comes with 100 short sounds a trigger can play by name, such as `confirmation_001` or `glass_002`: Kenney's
Interface Sounds (kenney.nl), which Kenney released into the public domain. F2 ▸ **sound** lists them as you type, the
window's sound field lists them all, and a full path to your own file still works.

## [0.3.10] - 2026-11-30

Expand Down
11 changes: 11 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,17 @@ fallbacks) for inline images/maps.
registered only when `PlaysMedia` is true (`TelnetSessionOptions.PlaysMsp`), because registering it is
the statement that this client plays sound; otherwise the server's `WILL MSP` is refused. Its two
callbacks raise `MspChanged`.
- **A trigger can play a local sound** (`TriggerActions.Sound`; Core `TriggerSound`, `WorldSession.SoundRequested`; Tui
`PlayTriggerSound` in `SharpMUTermApp.Sound.cs`; F2 `sound`, field 11, `TextRule.Sound`; the window's list editor adds
Choose… and Play, `SettingsForm.PlaySound`). A full path or `~/…` with one of `MediaCache.Extensions`, nothing fetched,
or a **built-in sound by name** (`BuiltInSounds`, Core: Kenney's Interface Sounds 1.0, 100 OGGs, CC0, embedded as
`sound/<name>` resources, `Media/Sounds/README.md`). A name is looked up whole, ignoring case, never made a path; it is
played from memory through `IAudioOutput.Play(Stream, name, start)`, so nothing is written to disk and every package
has it. The field's `Suggest` is the names: F2's dropdown (`DeclaredFields.Item`), the window's editable combo.
It goes straight to the device, not through a `MediaQueue` (no server rules apply), at master × sound level; F7's
`game sound` does not silence it (that is the world's), ⌃P ▸ Mute does. One voice per file: a repeat restarts it. A
missing or unplayable file is said once a run in the message log. F2's editor folds `set` onto its heading row only
when a short pane still overflows after compacting, so taller frames are unchanged.
- **Packages** (`Core/Packages`: `PackageManifest`, `PackageArchive`, `PackageStore`; Tui `PackageScreen`,
`ListOverlay`, `SharpMUTermApp.Packages.cs`). A `.zip` with `package.json` (id, name, SemVer version,
`games` as `host[:port]`, `*.host` or `*`), `sets/*.json`, `scripts/**.lua`, `media/**`; anything else is
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ cell, so a feature cannot land in one and not the other.
**Sound and alerts**
- MCMP and MSP sound through [SoundFlow](https://github.com/LSXPrime/SoundFlow), with captions when there is no
audio device.
- Triggers can play a sound of your own or one of 100 built-in ones (Kenney's Interface Sounds).
- Desktop alerts when you are paged or named while away, and a list of recent alerts.

**Accessibility**
Expand Down Expand Up @@ -209,6 +210,9 @@ The terminal client renders frames headlessly for checking layout without a term
The window bundles [Inter](https://rsms.me/inter/), [JetBrains Mono](https://www.jetbrains.com/lp/mono/) and
Symbols Nerd Font Mono, all under the SIL Open Font License.

The built-in trigger sounds are [Interface Sounds](https://kenney.nl/assets/interface-sounds) by
[Kenney](https://kenney.nl), CC0.

## More

- [`docs/PACKAGING.md`](docs/PACKAGING.md) and [`docs/RELEASING.md`](docs/RELEASING.md): how the packages and
Expand Down
59 changes: 49 additions & 10 deletions src/SharpMUTerm.Audio/DesktopAudio.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,40 @@ private static MiniAudioBackend[] Backends() =>
Stream? stream = null;
try
{
stream = Path.GetExtension(path).Equals(".ogg", StringComparison.OrdinalIgnoreCase)
? OggToWav(path)
: File.OpenRead(path);
stream = IsOgg(path) ? OggToWav(new NVorbis.VorbisReader(path)) : File.OpenRead(path);
}
catch (Exception ex) when (Unplayable(ex))
{
_logger?.LogInformation("Sound: could not play {File} ({Reason})", Path.GetFileName(path), ex.Message);
return null;
}

return Start(stream, Path.GetFileName(path), start);
}

public IAudioVoice? Play(Stream sound, string name, AudioStart start)
{
ArgumentNullException.ThrowIfNull(sound);
Stream stream;
try
{
stream = IsOgg(name) ? OggToWav(new NVorbis.VorbisReader(sound, closeOnDispose: true)) : sound;
}
catch (Exception ex) when (Unplayable(ex))
{
sound.Dispose();
_logger?.LogInformation("Sound: could not play {File} ({Reason})", name, ex.Message);
return null;
}

return Start(stream, name, start);
}

/// <summary>Plays a decodable <paramref name="stream"/>, which the voice then owns; disposed here when it cannot start.</summary>
private Voice? Start(Stream stream, string name, AudioStart start)
{
try
{
var provider = new StreamDataProvider(_engine, DeviceFormat, stream);
var player = new SoundPlayer(_engine, DeviceFormat, provider);
var voice = new Voice(this, player, provider, stream, start);
Expand All @@ -95,16 +126,20 @@ private static MiniAudioBackend[] Backends() =>
voice.Begin();
return voice;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException
or InvalidDataException or ArgumentException or NotSupportedException
or SoundFlow.Exceptions.BackendException)
catch (Exception ex) when (Unplayable(ex))
{
stream?.Dispose();
_logger?.LogInformation("Sound: could not play {File} ({Reason})", Path.GetFileName(path), ex.Message);
stream.Dispose();
_logger?.LogInformation("Sound: could not play {File} ({Reason})", name, ex.Message);
return null;
}
}

private static bool IsOgg(string name) => Path.GetExtension(name).Equals(".ogg", StringComparison.OrdinalIgnoreCase);

private static bool Unplayable(Exception ex) =>
ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException
or ArgumentException or NotSupportedException or SoundFlow.Exceptions.BackendException;

public void Dispose()
{
Voice[] voices;
Expand Down Expand Up @@ -137,9 +172,13 @@ private void Remove(Voice voice)
/// An OGG Vorbis file as a 16-bit PCM WAV in memory, at the file's own rate and channels, for miniaudio to
/// convert. Bounded by the cache's per-file cap on the compressed file, and by <paramref name="maxSeconds"/>.
/// </summary>
internal static MemoryStream OggToWav(string path, int maxSeconds = 20 * 60)
internal static MemoryStream OggToWav(string path, int maxSeconds = 20 * 60) =>
OggToWav(new NVorbis.VorbisReader(path), maxSeconds);

/// <summary>Decodes <paramref name="source"/> to a WAV in memory, then disposes it.</summary>
internal static MemoryStream OggToWav(NVorbis.VorbisReader source, int maxSeconds = 20 * 60)
{
using var reader = new NVorbis.VorbisReader(path);
using var reader = source;
var channels = reader.Channels;
var rate = reader.SampleRate;
if (channels is < 1 or > 8 || rate is < 4000 or > 192000)
Expand Down
105 changes: 104 additions & 1 deletion src/SharpMUTerm.Avalonia/ListEditorView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using SharpMUTerm.Client.Contributions;
using SharpMUTerm.Client.Settings;
using SharpMUTerm.Core.Configuration;
Expand Down Expand Up @@ -1154,6 +1155,9 @@ void Put(string value)
}
}

// Whether the last edit was refused and the stored value put back, until the box is edited again: Play reads it,
// so a refused replacement does not play the sound it failed to replace (leaving the box commits before the click).
var lastRefused = false;
void Commit()
{
if (_syncing || Current() == _form.Text(text))
Expand All @@ -1164,17 +1168,20 @@ void Commit()
if (_form.SetText(text, Current()) is { } refused)
{
// Refused by the rule the cell screen's field applies: put the value back and say why.
lastRefused = true;
Put(_form.Text(text));
ToolTip.SetTip(control, refused);
ToolTip.SetIsOpen(control, true);
}
else
{
lastRefused = false;
ToolTip.SetTip(control, NativeKeys.Words(text.Help));
}
}

control.LostFocus += (_, _) => Commit();
control.GotFocus += (_, _) => lastRefused = false;
if (auto is not null)
{
// A pick from the list commits as ⏎ would; typing commits on ⏎ or leaving the box.
Expand Down Expand Up @@ -1219,7 +1226,103 @@ void Commit()
ShowPreview(control.IsKeyboardFocusWithin ? Current() : null);
}
});
return control;
return text.Rule == TextRule.Sound
? SoundRow(text, control, Put, Commit, () =>
{
Commit();
var refused = lastRefused;
lastRefused = false;
return refused;
})
: control;
}

/// <summary>
/// A trigger's sound: the path box, then Choose… (the window's own open dialog, which fills the box and commits it
/// exactly as typing would, so the field's rule decides) and Play (the file once, at the level a match plays it).
/// </summary>
private Grid SoundRow(TextField text, Control box, Action<string> put, Action commit, Func<bool> commitRefused)
{
AutomationProperties.SetName(box, text.Label);
var choose = new Button { Content = "Choose…", VerticalAlignment = VerticalAlignment.Center };
AutomationProperties.SetName(choose, $"Choose a sound file for {text.Label}");
ToolTip.SetTip(choose, "Pick a .wav, .mp3, .ogg or .flac file");
choose.Click += async (_, _) =>
{
var (path, problem) = await PickSoundAsync();
if (path is not null)
{
put(path);
commit();
}
else if (problem is not null)
{
ToolTip.SetTip(box, problem);
ToolTip.SetIsOpen(box, true);
}
};

var play = new Button { Content = "Play", VerticalAlignment = VerticalAlignment.Center, IsVisible = _form.PlaySound is not null };
AutomationProperties.SetName(play, $"Play the {text.Label}");
ToolTip.SetTip(play, "Play the sound once, at your sound level");
play.Click += (_, _) =>
{
// What is typed is committed first, so Play plays the file the rule will; a path the rule refused plays nothing,
// not the sound it failed to replace.
if (!commitRefused() && _form.Text(text) is { Length: > 0 } stored)
{
_form.PlaySound?.Invoke(stored);
}
};

var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"), ColumnSpacing = NativeTokens.Space8 };
Grid.SetColumn(box, 0);
Grid.SetColumn(choose, 1);
Grid.SetColumn(play, 2);
row.Children.Add(box);
row.Children.Add(choose);
row.Children.Add(play);
return row;
}

/// <summary>
/// A sound file picked with the window's own open dialog: no path and no problem when it was cancelled, and a problem
/// when there is no dialog or the file has no path on this machine.
/// </summary>
private async Task<(string? Path, string? Problem)> PickSoundAsync()
{
if (TopLevel.GetTopLevel(this)?.StorageProvider is not { CanOpen: true } storage)
{
return (null, "this window has no file picker here: type the sound's full path instead");
}

try
{
var files = await storage.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "Choose a sound",
AllowMultiple = false,
FileTypeFilter =
[
new FilePickerFileType("Sounds")
{
Patterns = [.. SharpMUTerm.Core.Media.TriggerSound.Extensions.Select(e => "*" + e)],
},
],
});
if (files.Count == 0)
{
return (null, null);
}

return files[0].TryGetLocalPath() is { } local
? (local, null)
: (null, "that file has no path on this computer: save a copy locally and choose that");
}
catch (InvalidOperationException)
{
return (null, "the file picker could not open: type the sound's full path instead");
}
}

/// <summary>
Expand Down
9 changes: 9 additions & 0 deletions src/SharpMUTerm.Client/Settings/BuiltInLists.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using SharpMUTerm.Client.Contributions;
using SharpMUTerm.Core.Automation;
using SharpMUTerm.Core.Configuration;
using SharpMUTerm.Core.Media;
using SharpMUTerm.Core.Text;

namespace SharpMUTerm.Client.Settings;
Expand Down Expand Up @@ -173,6 +174,14 @@ public static partial class BuiltInSettings
ItemText<Trigger>("respond", "respond", TextRule.Template, ActionsGroup,
(_, t) => t.Actions.SendResponse, (_, t, v) => t.Actions.SendResponse = v,
"send this to the game; $1..$9 insert captures", NewTrigger, "send command reply"),
ItemText<Trigger>("sound", "sound", TextRule.Sound, ActionsGroup,
(_, t) => t.Actions.Sound, (_, t, v) => t.Actions.Sound = v,
"a sound to play: a built-in one by name (" + BuiltInSounds.Credit + "), or a full path to a .wav, .mp3, .ogg or .flac",
NewTrigger,
"audio play noise beep chime wav mp3 ogg flac file kenney") with
{
Suggest = (_, _) => BuiltInSounds.Names,
},
new TextField("script", "script", Help: "a Lua function to call")
{
Group = ActionsGroup,
Expand Down
5 changes: 5 additions & 0 deletions src/SharpMUTerm.Client/Settings/SettingsForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,11 @@ private void Commit(Action change, string? what)
/// </summary>
public Action<string, Core.Avatars.AvatarCrop>? PictureCropped { get; init; }

/// <summary>
/// Plays a trigger's sound file once, as a match would (the Play beside F2's <c>sound</c>). Null where nothing can play.
/// </summary>
public Action<string>? PlaySound { get; init; }

/// <summary>Undoes the last edit made on <paramref name="sectionId"/>; false when the client keeps no history.</summary>
public bool Undo(string sectionId) => Step(sectionId, redo: false);

Expand Down
7 changes: 7 additions & 0 deletions src/SharpMUTerm.Client/Settings/TextRules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ public enum TextRule
/// </summary>
Image,

/// <summary>
/// A trigger's sound (<see cref="Core.Media.TriggerSound"/>): blank for none, else a full path to a sound file that
/// exists; trimmed, and stored as null when blank.
/// </summary>
Sound,

/// <summary>
/// A world's WebSocket path (<see cref="Core.Transport.WebSocketAddress.IsPath"/>): blank for telnet, stored as null;
/// else starting with <c>/</c>; trimmed.
Expand Down Expand Up @@ -97,6 +103,7 @@ TextRule.Name or TextRule.Secret or TextRule.Defaulted when text.Any(char.IsCont
$"{field.Label} cannot contain control characters",
TextRule.Pattern when !string.IsNullOrWhiteSpace(text) => PatternError(text),
TextRule.Image => Core.Avatars.AvatarSource.Problem(text),
TextRule.Sound => Core.Media.TriggerSound.Problem(text),
TextRule.ScrollTail => Core.Configuration.ScrollTail.Problem(text),
TextRule.WebSocketPath when !string.IsNullOrWhiteSpace(text) && !Core.Transport.WebSocketAddress.IsPath(text.Trim()) =>
$"{field.Label} starts with / and holds no spaces or characters past ASCII",
Expand Down
8 changes: 8 additions & 0 deletions src/SharpMUTerm.Core/Automation/Trigger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ public sealed class TriggerActions
/// </summary>
public bool Alert { get; set; }

/// <summary>
/// A sound file to play when this rule matches (<see cref="Media.TriggerSound"/>: a full path on this machine), or
/// null for none. Played whether or not the line is gagged, at F7's sound level, and silenced by ⌃P ▸ Mute. Settable so
/// the F2 screen can change it live; the engine reads it per match.
/// </summary>
public string? Sound { get; set; }

/// <summary>
/// A copy of these actions. Every field is a value or an immutable string, so a member-wise copy
/// really is a deep one — but it has to be written out rather than shared, because
Expand All @@ -108,6 +115,7 @@ public sealed class TriggerActions
SpawnTarget = SpawnTarget,
ScriptCallback = ScriptCallback,
Alert = Alert,
Sound = Sound,
};
}

Expand Down
Loading
Loading