This project has moved. For the latest updates, please go here.

Error: "object reference not set to an instance of an object" in Naudio project

May 9, 2014 at 9:59 AM
Hi members
I am builiding a cut and join audio program and using Naudio reference.
I am building a media player. But see this error: Image while click ButtonPlay.
I do it. Because I want to get current time for cut audio
I don't this resolve!
Help me please!
Thanks
``` namespace CutAndJoin
{
public partial class MainForm : Form
{
    private IWavePlayer waveOut;
    private string fileName = null;
    private WaveStream fileWaveStream;
    private Action<float> setVolumeDelegate;
    private NAudio.Wave.BlockAlignReductionStream stream = null;
    private NAudio.Wave.DirectSoundOut output = null;

    public MainForm()
    {
        InitializeComponent();
    }


    public IEnumerable<IInputFileFormatPlugin> InputFileFormats { get; set; }        
    void OnPlaybackStopped(object sender, StoppedEventArgs e)
    {

        if (e.Exception != null)
        {
            MessageBox.Show(e.Exception.Message, "Playback Device Error");
        }
        fileWaveStream.Position = 0;
    }
    private void CloseWaveOut()
    {
        if (waveOut != null)
        {
            waveOut.Stop();
        }
        if (fileWaveStream != null)
        {
            // this one really closes the file and ACM conversion
            fileWaveStream.Dispose();
            this.setVolumeDelegate = null;
        }
        if (waveOut != null)
        {
            waveOut.Dispose();
            waveOut = null;
        }
    }

    private IInputFileFormatPlugin GetPluginForFile(string fileName)
    {
        var mp3Plugin = new Mp3InputFilePlugin();
        if (fileName.EndsWith(mp3Plugin.Extension))
        {
            return mp3Plugin;
        }
        var wavPlugin = new WaveInputFilePlugin();
        if (fileName.EndsWith(wavPlugin.Extension))
        {
            return wavPlugin;
        }
        var aiffPlugin = new AiffInputFilePlugin();
        if (fileName.EndsWith(aiffPlugin.Extension))
        {
            return aiffPlugin;
        }
        return null;
        //return (from f in this.InputFileFormats where fileName.EndsWith(f.Extension, StringComparison.OrdinalIgnoreCase) select f).FirstOrDefault();
    }
    private ISampleProvider CreateInputStream(string fileName)
    {
        var plugin = GetPluginForFile(fileName);
        if (plugin == null)
        {
            throw new InvalidOperationException("Unsupported file extension");
        }
        this.fileWaveStream = plugin.CreateWaveStream(fileName);
        var waveChannel = new SampleChannel(this.fileWaveStream);
        this.setVolumeDelegate = (vol) => waveChannel.Volume = vol;
        waveChannel.PreVolumeMeter += OnPreVolumeMeter;

        var postVolumeMeter = new MeteringSampleProvider(waveChannel);
        postVolumeMeter.StreamVolume += OnPostVolumeMeter;

        return postVolumeMeter;
    }
    void OnPreVolumeMeter(object sender, StreamVolumeEventArgs e)
    {
        // we know it is stereo
        waveformPainter1.AddMax(e.MaxSampleValues[0]);
        waveformPainter2.AddMax(e.MaxSampleValues[1]);
    }

    void OnPostVolumeMeter(object sender, StreamVolumeEventArgs e)
    {
        // we know it is stereo
        volumeMeter1.Amplitude = e.MaxSampleValues[0];
        volumeMeter2.Amplitude = e.MaxSampleValues[1];
    }
    private void CreateWaveOut()
    {
        CloseWaveOut();
        //int latency = (int)comboBoxLatency.SelectedItem;
        //this.waveOut = SelectedOutputDevicePlugin.CreateDevice(latency);
    }


    private void buttonPlay_Click(object sender, EventArgs e)
    {


        if (waveOut != null)
        {
            if (waveOut.PlaybackState == PlaybackState.Playing)
            {
                return;
            }
            else if (waveOut.PlaybackState == PlaybackState.Paused)
            {
               waveOut.Play();

                return;
            }
        }
        // we are in a stopped state
        // TODO: only re-initialise if necessary

        if (String.IsNullOrEmpty(fileName))
        {
            OnOpenFileClick(sender, e);
        }
        if (String.IsNullOrEmpty(fileName))
        {
            return;
        }

        try
        {
            CreateWaveOut();
        }
        catch (Exception driverCreateException)
        {
            MessageBox.Show(String.Format("{0}", driverCreateException.Message));
            return;
        }


        ISampleProvider sampleProvider = null;
        try
        {
            sampleProvider = CreateInputStream(fileName);
        }
        catch (Exception createException)
        {
            MessageBox.Show(String.Format("{0}", createException.Message), "Error Loading File");
            return;
        }

        trackBarPosition.Maximum = (int)fileWaveStream.TotalTime.TotalSeconds;
        labelTotalTime.Text = String.Format("{0:00}:{1:00}", (int)fileWaveStream.TotalTime.TotalMinutes,
          fileWaveStream.TotalTime.Seconds);
        trackBarPosition.TickFrequency = trackBarPosition.Maximum / 30;
        try
        {
            waveOut.Init(new SampleToWaveProvider(sampleProvider));
        }
        catch (Exception initException)
        {
            MessageBox.Show(String.Format("{0}", initException.Message), "Error Initializing Output");
            return;
        }



        setVolumeDelegate(volumeSlider1.Volume);

        waveOut.Play();


    }

    private void buttonPause_Click(object sender, EventArgs e)
    {
        if (output != null)
        {
            if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Pause();
            else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused) output.Play();


        }
    }
    private void DisposeWave()
    {
        if (output != null)
        {
            if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Stop();
            output.Dispose();
            output = null;
            if (stream != null)
            {
                stream.Dispose();
                stream = null;

            }
        }
    }

    private void buttonStop_Click(object sender, EventArgs e)
    {
        if (waveOut != null)
        {
            waveOut.Stop();
        }
    }

    private void trackBarPosition_Scroll(object sender, EventArgs e)
    {
        if (waveOut != null)
        {
            fileWaveStream.CurrentTime = TimeSpan.FromSeconds(fileWaveStream.TotalTime.TotalSeconds * trackBarPosition.Value / 100.0);
        }
    }
    private void volumeSlider1_VolumeChanged(object sender, EventArgs e)
    {
        if (setVolumeDelegate != null)
        {
            setVolumeDelegate(volumeSlider1.Volume);
        }
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (waveOut != null && fileWaveStream != null)
        {
            TimeSpan currentTime = (waveOut.PlaybackState == PlaybackState.Stopped) ? TimeSpan.Zero : fileWaveStream.CurrentTime;
            trackBarPosition.Value = Math.Min(trackBarPosition.Maximum, (int)(100 * currentTime.TotalSeconds / fileWaveStream.TotalTime.TotalSeconds));
            labelCurrentTime.Text = String.Format("{0:00}:{1:00}", (int)currentTime.TotalMinutes,
                currentTime.Seconds);
        }
        else
        {
            trackBarPosition.Value = 0;
        }
    }

    private void timer1_Tick_1(object sender, EventArgs e)
    {
        if (waveOut != null && fileWaveStream != null)
        {
            TimeSpan currentTime = (waveOut.PlaybackState == PlaybackState.Stopped) ? TimeSpan.Zero : fileWaveStream.CurrentTime;
            trackBarPosition.Value = Math.Min(trackBarPosition.Maximum, (int)(100 * currentTime.TotalSeconds / fileWaveStream.TotalTime.TotalSeconds));
            labelCurrentTime.Text = String.Format("{0:00}:{1:00}", (int)currentTime.TotalMinutes,
                currentTime.Seconds);
        }
        else
        {
            trackBarPosition.Value = 0;
        }
    }
private void OnOpenFileClick(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();

        openFileDialog.FilterIndex = 1;
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = openFileDialog.FileName;
        }
    }



Coordinator
May 12, 2014 at 8:21 PM
Visual Studio should tell you which line the null reference exception was on.
May 20, 2014 at 7:58 AM
Can I fix this error ?
Get a solution to me, please!
Thanks
Coordinator
May 20, 2014 at 8:09 AM
you need to provide us with a stack trace. Call .ToString on the exception and paste the result here