Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve error text for MmResult in MmException #1192

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
28 changes: 27 additions & 1 deletion NAudio.Core/MmException.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace NAudio
{
Expand All @@ -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
/// <summary>
/// The waveOutGetErrorText function retrieves a textual description of the error identified by the given error number.
/// </summary>
/// <param name="mmrError">Error number.</param>
/// <param name="pszText">Pointer to a buffer to be filled with the textual error description.</param>
/// <param name="cchText">Size, in characters, of the buffer pointed to by pszText.</param>
/// <returns>Returns MMSYSERR_NOERROR if successful or an error otherwise.</returns>
[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)}";
}

/// <summary>
Expand Down