这个例子实现了在用户指定的设备上播放音频。比如,可以选择从耳机中播放。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio;
using NAudio.Wave;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
for (int n = 0; n < WaveOut.DeviceCount; n++)
{
Console.WriteLine(n + " : " + WaveOut.GetCapabilities(n).ProductName);
}
while (true)
{
int i = 0;
do
{
Console.WriteLine("Choose device:");
} while (!int.TryParse(Console.ReadLine(), out i) || i >= WaveOut.DeviceCount || i < 0);
WaveOutEvent waveOutEvent = new WaveOutEvent();
waveOutEvent.DeviceNumber = i;
Console.WriteLine("Play on "+WaveOut.GetCapabilities(i).ProductName);
using (var audioFileReader = new AudioFileReader(@"c:\temp\1990.mp3"))
{
// Play mp3 in the device
waveOutEvent.Init(audioFileReader);
waveOutEvent.Play();
// Wait until the end
while (waveOutEvent.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(100);
}
}
}
}
}
}