问题
I'm using the naudio lib in C# and want to play a simple file. The problem is, the playback stops after 1 second. I cant figure out the reason why it does that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAudio.Wave;
namespace NAudioTest
{
class Program
{
static IWavePlayer waveout;
static WaveStream outputStream;
static string filename = null;
static void Main(string[] args)
{
waveout = new WaveOut();
filename = "C:\\1.wav";
outputStream = CreateInputStream(filename);
try
{
waveout.Init(outputStream);
}
catch (Exception ex)
{
Console.WriteLine("Error while loading output");
Console.WriteLine("Details: " + ex.Message);
Console.ReadLine();
return;
}
Console.WriteLine("Press [Enter] to start playback");
Console.ReadLine();
waveout.Play(); //this stops after 1 sec. should it play until i hit enter cause of the next line?
Console.WriteLine("Press [Enter] to abort");
Console.ReadLine();
waveout.Dispose();
Console.ReadLine();
}
static WaveStream CreateInputStream(string name)
{
WaveChannel32 inputStream;
if (name.EndsWith(".wav"))
{
WaveStream readerStream = new WaveFileReader(name);
if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
{
readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
readerStream = new BlockAlignReductionStream(readerStream);
}
if (readerStream.WaveFormat.BitsPerSample != 16)
{
var format = new WaveFormat(readerStream.WaveFormat.SampleRate, 16, readerStream.WaveFormat.Channels);
readerStream = new WaveFormatConversionStream(format, readerStream);
}
inputStream = new WaveChannel32(readerStream);
}
else
{
throw new InvalidOperationException("Invalid extension");
}
return inputStream;
}
}
}
回答1:
You need to make sure you are using function callbacks if you are trying to play audio from a console app, since the default for WaveOut is to use window callbacks.
new WaveOut(WaveCallbackInfo.FunctionCallback())
Update: With newer versions of NAudio I now recommend that you avoid function callbacks, as they can cause deadlocks with certain drivers. Instead, WaveOutEvent
which uses event callbacks and a background thread is the preferred mechanism:
new WaveOutEvent()
来源:https://stackoverflow.com/questions/4391409/playing-a-wav-file-using-naudio-playback-stops-after-1-sec