我想分享有关如何创建控制台C#应用程序以使用NAudio库播放wav音频文件的信息。我现在唯一的问题是音频文件播放结束时 - 成功终止应用程序需要大约1秒。这可能是因为NAudio lib需要一些时间来从音频数据中释放内存。希望它对某人有所帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using NAudio.Wave;
using NAudio.CoreAudioApi;
namespace WaveTestNew
{
class Program
{
static public WaveOut waveOut = new WaveOut();
static public WaveFileReader reader = null;
public static void printDevices()
{
Console.WriteLine("\nAvailable devices id:");
for (int i = 0; i < WaveOut.DeviceCount; i++)
{
WaveOutCapabilities WOC = WaveOut.GetCapabilities(i);
Console.WriteLine(i + " = " + WOC.ProductName);
}
}
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Input parameters: <file_name> <device_id>");
Console.WriteLine(@"Example:\n >>wavplay.exe c:\temp\test.wav 1");
printDevices();
Environment.Exit(1);
}
int iDeviceID = int.Parse(args[1]);
if (iDeviceID >= WaveOut.DeviceCount)
{
Console.WriteLine("ERROR - unknown device_id: " + iDeviceID);
printDevices();
Environment.Exit(2);
}
String fileName = args[0];
if (!fileName.ToLower().EndsWith(".wav"))
{
Console.WriteLine("ERROR: Not supported media file format");
Environment.Exit(3);
}
waveOut.DeviceNumber = iDeviceID; // for default device
reader = new WaveFileReader(fileName);
waveOut.PlaybackStopped += waveOut_PlaybackStopped;
waveOut.Init(reader);
Console.WriteLine(DateTime.Now + ":Playback start");
waveOut.Play();
while (waveOut.PlaybackState != PlaybackState.Stopped)
{
Thread.Sleep(100);
}
Console.WriteLine(DateTime.Now + ":Playback stop");
return;
}
private static void waveOut_PlaybackStopped(object sender, StoppedEventArgs e)
{
reader.Dispose();
waveOut.Dispose();
}
}
}
答案 0 :(得分:1)