nullReferenceException when i try to play a sound

2019-09-02 10:22发布

问题:

I'm making a soundboard with sound effects and I'm getting :

"A first chance exception of type 'System.NullReferenceException'" 
   when building after 'UI Task' (Managed): 
   Loaded 'Microsoft.Xna.Framework.dll'

I did have it working but after changes (overwrote previous version) I have been getting this error and I'm stuck. Java is my first language and with C# I'm a beginner. I have spent countless hours looking for a solution.

The nullReferenceException is coming from loadsound(), I think! I have the sound files(.wav) in a folder called resources and build action:resources and copy to output:do not copy(have tried all options here). Also in references a reference was made to Microsoft.Xna.Framework

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Resources;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;

namespace Craggy_Island
{
    public partial class MainPage : PhoneApplicationPage
    {
        // The Resources to play
        private SoundEffect drink;//(plus 23 more effects)

        // Flag that indicates if we need to resume Zune playback upon exiting.
        bool resumeMediaPlayerAfterDone = false;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Timer to simulate the XNA game loop (SoundEffect class is from the XNA Framework)
            GameTimer gameTimer = new GameTimer();
            gameTimer.UpdateInterval = TimeSpan.FromMilliseconds(33);

            // Call FrameworkDispatcher.Update to update the XNA Framework internals.
            gameTimer.Update += delegate { try { FrameworkDispatcher.Update(); } catch { } };

            // Start the GameTimer running.
            gameTimer.Start();

            // Prime the pump or we'll get an exception.
            FrameworkDispatcher.Update();

            //LoadSound("Resources/drink.wav", out drink);
            // Create and load SoundEffect objects.
            LoadSound("Resources/drink.wav", out drink);

        }

        private void LoadSound(String SoundFilePath, out SoundEffect Sound)
        {
            // For error checking, assume we'll fail to load the file.
            Sound = null;

            try
            {
                // Holds informations about a file stream.
                StreamResourceInfo SoundFileInfo = App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));

                // Create the SoundEffect from the Stream
                Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
            }
            catch (NullReferenceException)
            {
                // Display an error message
                MessageBox.Show("Couldn't load sound " + SoundFilePath);
            }
        }



        private void button_Click(object sender, RoutedEventArgs e)
        {
            Button Current = sender as Button;

            try
            {
                if (Current.Equals(button1))
                    drink.Play();//(other buttons here for other sound effects)



            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Can't play, sound file problem.");
            }

        }
        #region Zune Pause/Resume

        private void ZunePause()
        {
            // Please see the MainPage() constructor above where the GameTimer object is created.
            // This enables the use of the XNA framework MediaPlayer class by pumping the XNA FrameworkDispatcher.

            // Pause the Zune player if it is already playing music.
            if (!MediaPlayer.GameHasControl)
            {
                MediaPlayer.Pause();
                resumeMediaPlayerAfterDone = true;
            }
        }

        private void ZuneResume()
        {
            // If Zune was playing music, resume playback
            if (resumeMediaPlayerAfterDone)
            {
                MediaPlayer.Resume();
            }
        }

        #endregion Zune Pause/Resume

    }
}

回答1:

Scrap my original answer unless you're using XNA for game development on Windows/Xbox. (Original poster is using it for the Zune.)

Regarding the WAV file:

First problem is that you need to set Copy to Output Directory to Copy if newer. (You could use Always, but that would be unnecessary.)

Second problem is that its type needs to be set to Content.



回答2:

You are taking the hard approach. Look into ContentManager (accessible as this.Content from within the Game instance). You can use Content.Load<T>(string) to access your audio file, but you'll need to put the audio file in the content project. Don't change its type: leave it at the default. Even it's not a resource, leave it be. It will be compiled into a different format. Also, omit the file extension from the parameter passed to Content.Load<>.



回答3:

You are starting the game before you are loading the sound:

gameTimer.Start();

FrameworkDispatcher.Update();

LoadSound("Resources/drink.wav", out drink);


回答4:

I had almost the same problem. Finally I got it accidently as follows:

StreamResourceInfo streaminfo = Application.GetResourceStream(new Uri("project_name;component/folder_name/Sound3.wav", UriKind.RelativeOrAbsolute));
SoundEffect effect1 = SoundEffect.FromStream(streaminfo.Stream);
effect1.Play();

AND: the Property "Build Action" of the .wav file must be setted to "Resource" and the Porperty "Copy to Output Directory" should be setted to "Copy if newer"

By the way, I´m working with Silverlight5.