0%

20220702-NAudio 雜記 and VS Code 常用快速鍵 備忘

20220702-NAudio 雜記

VS Code 常用快速鍵 備忘

解決 NAudio 轉 mp3 檔案時出現的 COMException

  • 執行 MediaFoundationEncoder.EncodeToMp3 時出現以下錯誤訊息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
未處理的例外狀況: System.Runtime.InteropServices.COMException: 因為已呼叫 Shutdown(),所以要求無效。 (發生例外狀況於 HRESULT: 0xC00D3E85)
於 NAudio.MediaFoundation.MediaFoundationInterop.MFCreateSinkWriterFromURL(String pwszOutputURL, IMFByteStream pByteStream, IMFAttributes pAttributes, IMFSinkWriter& ppSinkWriter)
於 NAudio.Wave.MediaFoundationEncoder.CreateSinkWriter(String outputFile)
於 NAudio.Wave.MediaFoundationEncoder.Encode(String outputFile, IWaveProvider inputProvider)
於 NAudio.Wave.MediaFoundationEncoder.EncodeToMp3(IWaveProvider inputProvider, String outputFile, Int32 desiredBitRate)
於 HccMsCognitiveServicesTester.Program.<>c__DisplayClass2_1.<ConvertWavToMp3Async>b__0()
於 System.Threading.Tasks.Task.Execute()
--- 先前擲回例外狀況之位置中的堆疊追蹤結尾 ---
於 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
於 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
於 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
於 HccMsCognitiveServicesTester.Program.<ConvertWavToMp3Async>d__2.MoveNext()
--- 先前擲回例外狀況之位置中的堆疊追蹤結尾 ---
於 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
於 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
於 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
於 HccMsCognitiveServicesTester.Program.<Main>d__1.MoveNext()
--- 先前擲回例外狀況之位置中的堆疊追蹤結尾 ---
於 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
於 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
於 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
於 HccMsCognitiveServicesTester.Program.<Main>(String[] args)
  • 根據錯誤訊息,找到以下文章及解法
    The request is invalid because Shutdown() has been called. (Exception from HRESULT: 0xC00D3E85)

  • 英文錯誤訊息

    1
    System.Runtime.InteropServices.COMException: 'The request is invalid because Shutdown() has been called. (Exception from HRESULT: 0xC00D3E85)'
  • 參考解法

    1
    2
    3
    4
    5
    6
    using (var wfr = new WaveFileReader(ms))
    {
    MediaFoundationApi.Startup();
    MediaFoundationEncoder.EncodeToMp3(wfr, @"C:\Temp\Test.mp3", 160000);
    MediaFoundationApi.Shutdown();
    }

Task / async 寫法練習

本日最終寫法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static async Task ConvertWavToMp3Async(string wavPath, string mp3Path)
{
using (var reader = new WaveFileReader(wavPath))
{
try
{
await Task.Run(() =>
{
MediaFoundationApi.Startup();
MediaFoundationEncoder.EncodeToMp3(reader, mp3Path);
MediaFoundationApi.Shutdown();
});
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
}
}

VS Code 常用快速鍵 備忘

CodePen / VS Code 常用快速鍵
往前縮排: Shift + tab