From 13a2f09d2436269edb7f33ccbcc6bad7a31694c3 Mon Sep 17 00:00:00 2001 From: Tim Horemans Date: Wed, 30 Oct 2024 12:01:47 +0100 Subject: [PATCH] Retrieve error text for MmResult in MmException --- NAudio.Core/MmException.cs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/NAudio.Core/MmException.cs b/NAudio.Core/MmException.cs index 26dd5d05..e7143a43 100644 --- a/NAudio.Core/MmException.cs +++ b/NAudio.Core/MmException.cs @@ -1,4 +1,6 @@ using System; +using System.Runtime.InteropServices; +using System.Text; namespace NAudio { @@ -19,10 +21,34 @@ public MmException(MmResult result, string function) Function = function; } + private const int ErrorTextMaxLength = 256; + + // https://learn.microsoft.com/en-us/windows/win32/api/mmeapi/nf-mmeapi-waveoutgeterrortext + /// + /// The waveOutGetErrorText function retrieves a textual description of the error identified by the given error number. + /// + /// Error number. + /// Pointer to a buffer to be filled with the textual error description. + /// Size, in characters, of the buffer pointed to by pszText. + /// Returns MMSYSERR_NOERROR if successful or an error otherwise. + [DllImport("winmm.dll", CharSet = CharSet.Auto)] + private static extern MmResult waveOutGetErrorText(MmResult mmrError, StringBuilder pszText, uint cchText); + + private static string GetErrorText(MmResult result) + { + var sb = new StringBuilder(ErrorTextMaxLength); + var textResult = waveOutGetErrorText(result, sb, ErrorTextMaxLength); + if (textResult == MmResult.NoError) + { + return sb.ToString(); + } + + return textResult.ToString(); + } private static string ErrorMessage(MmResult result, string function) { - return $"{result} calling {function}"; + return $"{result} calling {function}: {GetErrorText(result)}"; } ///