使用naudio播放.wav文件,播放在1秒后停止

时间:2010-12-08 19:24:07

标签: c# .net naudio

我在C#中使用naudio lib并想播放一个简单的文件。问题是,播放在1秒后停止。我无法弄清楚它为什么会这样做。

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 个答案:

答案 0 :(得分:7)

如果您尝试从控制台应用播放音频,则需要确保使用函数回调,因为WaveOut的默认设置是使用窗口回调。

new WaveOut(WaveCallbackInfo.FunctionCallback())

更新:对于较新版本的NAudio,我现在建议您避免使用函数回调,因为它们可能会导致某些驱动程序出现死锁。相反,使用事件回调和后台线程的WaveOutEvent是首选机制:

new WaveOutEvent()