C# 撥放音效不影響主程序繼續UI渲染的執行
C# 撥放音效不影響主程序繼續UI渲染的執行
資料來源: https://gemini.google.com/share/8e1ad1080a40
原本程式:
public static void PayTakeawaysSound()//外帶聲音播放函數
{
String StrPath = (App.m_blnParentDir) ? Directory.GetParent(LogFile.m_StrSysPath.Substring(0, LogFile.m_StrSysPath.Length - 1)).FullName + "\\" : LogFile.m_StrSysPath;
string filePath = StrPath + "takeaways_sound.wav";
// 檢查檔案是否存在
if (!System.IO.File.Exists(filePath))
{
return;
}
try
{
// 1. 讀取 WAV 檔案
using (var audioFile = new AudioFileReader(filePath))
// 2. 建立輸出裝置 (WaveOutEvent 支援非同步播放)
using (var outputDevice = new WaveOutEvent())
{
// 3. 將音訊檔案連接到輸出裝置
outputDevice.Init(audioFile);
// 4. 開始播放
outputDevice.Play();
// 對於 Console 應用程式:等待播放完成
while (outputDevice.PlaybackState == PlaybackState.Playing)
{
// 稍作等待
System.Threading.Thread.Sleep(100);
}
}
}
catch (Exception ex)
{
LogFile.Write("PayTakeawaysSound Error:" + ex.Message);
return;
}
}
修改後的程式(使用Task.Run包覆):
public static void PayTakeawaysSound()//外帶聲音播放函數
{
// 在背景執行,不阻塞主程序
Task.Run(() =>
{
String StrPath = (App.m_blnParentDir) ? Directory.GetParent(LogFile.m_StrSysPath.Substring(0, LogFile.m_StrSysPath.Length - 1)).FullName + "\\" : LogFile.m_StrSysPath;
string filePath = StrPath + "takeaways_sound.wav";
// 檢查檔案是否存在
if (!System.IO.File.Exists(filePath))
{
return;
}
try
{
// 1. 讀取 WAV 檔案
using (var audioFile = new AudioFileReader(filePath))
// 2. 建立輸出裝置 (WaveOutEvent 支援非同步播放)
using (var outputDevice = new WaveOutEvent())
{
// 3. 將音訊檔案連接到輸出裝置
outputDevice.Init(audioFile);
// 4. 開始播放
outputDevice.Play();
// 對於 Console 應用程式:等待播放完成
while (outputDevice.PlaybackState == PlaybackState.Playing)
{
// 稍作等待
System.Threading.Thread.Sleep(100);
}
}
}
catch (Exception ex)
{
LogFile.Write("PayTakeawaysSound Error:" + ex.Message);
return;
}
});
}