This question already has answers here:
What is a NullReferenceException, and how do I fix it?

(28个答案)


去年关闭。




我正在使用Naudio在C#中创建自己的软件合成器,并首先生成一些简单的正弦波,然后播放它们。我想自己做,而不是使用Naudio的内置SignalGenerator
将我的自定义对象sine传递给ISampleProvider生成正弦波(实现WaveOutEvent.Init)时,我被抛出了NullReferenceException。在调用init之前,我已经创建了SineWave类的实例,但是仍然可以得到NullReferenceException

我已经使用WaveOutEvent命令测试了我的wo(SineWave)和sine(null)对象是否都是if,例如:
if (sineWave != null)
{
    Console.WriteLine("sine is not null");
}
if (waveOut != null)
{
    Console.WriteLine("wo is not null");
}

这两个语句均通过,并且sine is not nullwo is not null均写入控制台。
namespace AddSynth
{
    public class SineWave : ISampleProvider
    {
        public WaveFormat WaveFormat { get; }
        int frequency = 440;
        int sampleRate = 44100;
        double amp = 0.25;
        int phase = 0;
        public int Read(float[] buffer, int offset, int count)
        {
            int sampleCount = sampleRate / frequency;
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = (float)(amp * Math.Sin(2 * Math.PI * frequency * i + phase));
            }
            return sampleCount;
        }
    }

    public class Playback
    {
        static void Main()
        {
            Playback playBack = new Playback();
            playBack.playAudio();
        }

        public void playAudio()
        {
            WaveOutEvent waveOut = new WaveOutEvent();
            SineWave sineWave = new SineWave();
            if (sineWave != null)
            {
                Console.WriteLine("sine is not null");
            }
            if (waveOut != null)
            {
                Console.WriteLine("wo is not null");
            }
            waveOut.Init(sineWave.ToWaveProvider());
            waveOut.Play();
            Console.ReadKey();
        }
    }
}

我希望通过计算机的音频播放正弦波。我希望我已经添加了足够的信息。

编辑:刚意识到,我可能也应该添加堆栈跟踪,所以在这里,如果有帮助:
   at NAudio.Wave.SampleProviders.SampleToWaveProvider..ctor(ISampleProvider source)
   at NAudio.Wave.WaveExtensionMethods.ToWaveProvider(ISampleProvider sampleProvider)
   at AddSynth.Playback.playAudio() in C:\Users\User1\source\repos\AddSynth\AddSynth\Program.cs:line 44
   at AddSynth.Playback.Main() in C:\Users\User1\source\repos\AddSynth\AddSynth\Program.cs:line 29

最佳答案

正如Nkosi所说,问题在于我从未分配WaveFormat变量。

关于c# - 尝试在Naudio(C#)中播放ISampleProvider时获取NullReferenceException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56918167/

10-11 10:29