9public static class NAudioReaderRegistry
11 private sealed record Registration(Func<Stream, WaveStream>? StreamFactory, Func<string, WaveStream>? FileFactory);
13 private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, Registration> Readers =
new(
14 StringComparer.OrdinalIgnoreCase);
16 static NAudioReaderRegistry()
18 Register(
".wav", stream =>
new WaveFileReader(stream));
19 Register(
".mp3", stream =>
new Mp3FileReader(stream));
20 Register(
".ogg", stream =>
new VorbisWaveReader(stream));
21 Register(
".oga", stream =>
new VorbisWaveReader(stream));
22 Register(
".mogg", stream =>
new VorbisWaveReader(stream));
23 RegisterFile(
".wma", path =>
new MediaFoundationReader(path));
24 RegisterFile(
".m4a", path =>
new MediaFoundationReader(path));
34 public static void Register(
string extension, Func<Stream, WaveStream> readerFactory)
36 ArgumentNullException.ThrowIfNull(readerFactory);
37 Readers[NormalizeExtension(extension)] =
new Registration(readerFactory,
null);
47 public static void RegisterFile(
string extension, Func<string, WaveStream> readerFactory)
49 ArgumentNullException.ThrowIfNull(readerFactory);
50 Readers[NormalizeExtension(extension)] =
new Registration(
null, readerFactory);
58 public static bool Supports(
string fileNameOrExtension) => Readers.ContainsKey(GetExtension(fileNameOrExtension));
64 public static IEnumerable<string> SupportedExtensions() => Readers.Keys.OrderBy(ext => ext);
66 internal static (WaveStream Reader,
string? TemporaryFilePath) Open(
byte[] data,
string fileNameOrExtension)
68 var extension = GetExtension(fileNameOrExtension);
70 if (!Readers.TryGetValue(extension, out var registration))
71 throw new NotSupportedException($
"Format '{extension}' is not supported by Gondwana.Audio.NAudio.");
73 if (registration.StreamFactory is not
null)
75 var stream =
new MemoryStream(data, writable:
false);
79 return (registration.StreamFactory(stream),
null);
88 var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + extension);
92 File.WriteAllBytes(tempPath, data);
93 return (registration.FileFactory!(tempPath), tempPath);
102 private static string GetExtension(
string fileNameOrExtension)
104 var extension = Path.GetExtension(fileNameOrExtension);
106 if (
string.IsNullOrWhiteSpace(extension) &&
107 !fileNameOrExtension.Contains(
'/') && !fileNameOrExtension.Contains(
'\\'))
108 extension = fileNameOrExtension;
110 return NormalizeExtension(extension);
113 private static string NormalizeExtension(
string? extension)
115 if (
string.IsNullOrWhiteSpace(extension))
116 throw new InvalidOperationException(
"Audio source has no file extension.");
118 return extension.StartsWith(
'.') ? extension.ToLowerInvariant() :
"." + extension.ToLowerInvariant();
121 internal static void TryDelete(
string? path)
123 if (
string.IsNullOrWhiteSpace(path))
128 if (File.Exists(path))