播放声音时NAudio AccessViolationException

时间:2012-03-06 14:47:06

标签: c# naudio

我正在使用NAudio在我的程序中播放多个声音。问题是程序在一段时间后随机崩溃,似乎是由声音引起的。

我正在使用以下Stacktrace获得System.AccessViolationException

bei NAudio.Wave.DirectSoundOut.IDirectSoundBuffer.Stop()

bei NAudio.Wave.DirectSoundOut.StopPlayback()

bei NAudio.Wave.DirectSoundOut.PlaybackThreadFunc()

bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)

bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

bei System.Threading.ThreadHelper.ThreadStart()


Void Stop()

bei NAudio.Wave.DirectSoundOut.IDirectSoundBuffer.Stop()

bei NAudio.Wave.DirectSoundOut.StopPlayback()

bei NAudio.Wave.DirectSoundOut.PlaybackThreadFunc()

bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)

bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

bei System.Threading.ThreadHelper.ThreadStart()

我正在使用以下代码:

class SLMBSoundOut : DirectSoundOut {
    public WaveStream stream;
    public SLMBSoundOut(String file, float vol = 1.0f)
        : base(200) {

        stream = CreateInputStream(file, vol);
        this.Init(stream);
    }

    private WaveStream CreateInputStream(string fileName, float vol) {
        WaveChannel32 inputStream;
        if (fileName.EndsWith(".wav")) {
            WaveStream readerStream = new WaveFileReader(fileName);
            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);
            inputStream.Volume = vol;

        } else {
            throw new InvalidOperationException("Unsupported extension");
        }
        inputStream.PadWithZeroes = false;
        return inputStream;
    }

}

播放声音,即时通讯使用此方法

private static void playResource(string res) {
        if (SLMB.Data.Constants.SOUND_ENABLED) {
            SLMBSoundOut player;
            player = new SLMBSoundOut(Directory.GetCurrentDirectory() + res);
            player.Play();
        }
    }

此外还有背景音乐,通过使用PlaybackStopped-Event重复自我:

ambience.PlaybackStopped += new EventHandler(ambienceStopped);


private static void ambienceStopped(object sender, EventArgs args) {
        if (SLMB.Data.Constants.SOUND_ENABLED) {
            ambience.stream.Position = 0;
            ambience.Play();
        }
    }

有没有人知道出了什么问题?

0 个答案:

没有答案