.net c#尝试播放声音时给出Null参考异常

Null Reference Exception being given when trying to play sound
2020-11-24
  •  译文(汉语)
  •  原文(英语)

每当我的游戏中有比赛时,我都试图插入声音.但是,当我得到比赛时,我一直得到NullReferenceException.转到行soundEffectInstance.Play();.任何帮助是极大的赞赏.在尝试使其正常工作时,我已经做了所有尝试.这是我的代码:

using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;

namespace AndyKlax.KlaxGame
{
internal class Grid
{
    private const int GridOrigin = 660;


    SoundEffect soundEffect;
    SoundEffectInstance soundEffectInstance;


    private readonly List<Block>[] _grid = new List<Block>[Klax.NumberOfColumns];

    public void LoadContent(ContentManager content)
    {

        soundEffect = content.Load<SoundEffect>(@"Sounds/24372^pop2.mp3");
        soundEffectInstance = soundEffect.CreateInstance();

    }

    internal Grid()
    {
        for (int i = 0; i < Klax.NumberOfColumns; i++ )
        {
            _grid[i] = new List<Block>();
        }
    }

    private bool RemoveBlocks()
    {
        var foundBlocksToRemove = false;

        //Mark all blocks in the grid as unmatched
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row =_grid[column].Count -1 ; row >=0 ; row--) //Loop backwards do its safe to remove
            {
                if (_grid[column][row].Delete)
                {
                    _grid[column].RemoveAt(row);
                    foundBlocksToRemove = true;
                }
            }
        }

        return foundBlocksToRemove;
    }



    private void SearchForMatches()
    {

        //Search the whole grid - look for matches in each direction and set the deleted flag for anything you find
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row = 0; row < _grid[column].Count; row++)
            {
                SearchForMatches(column, row, 1, 0);  //Horizontal
                SearchForMatches(column, row, 0, 1);  //Vertical
                SearchForMatches(column, row, 1, 1);  //Diagonal one way
                SearchForMatches(column, row, 1, -1);  //Diagonal the other way
            }
        }
    }

    private void SearchForMatches(int column, int row, int xStep, int yStep)
    {


        int startColorIndex = _grid[column][row].ColorIndex;
        int matchCount = 0;

        int x = column;
        int y = row;

        //Loop in the given direction till we run out of color or grid
        do
        {
            matchCount++;
            x += xStep;
            y += yStep;

        } while (x < Klax.NumberOfColumns && y < _grid[x].Count && y>0 && startColorIndex == _grid[x][y].ColorIndex);

        //If the match is long enough 
        if (matchCount >= 3)
        {
            //Then mark all those blocks for removal
            x = column;
            y = row;

            //Loop in the given direction till we run out of color or grid
            do
            {
                _grid[x][y].Delete = true;

                x += xStep;
                y += yStep;
                soundEffectInstance.Play();

            } while (x < Klax.NumberOfColumns && y < _grid[x].Count && startColorIndex == _grid[x][y].ColorIndex);
        }
    }

    private void ResetDeleteFlags()
    {
        //Mark all blocks in the grid as unmatched
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row = 0; row < _grid[column].Count; row++)
            {
                _grid[column][row].Delete = false;
            }
        }
    }

    internal void Draw(SpriteBatch spriteBatch)
    {
        //Like the paddle the position of the block is inferred by its position in the grid
        spriteBatch.Begin();
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row = 0; row < _grid[column].Count; row++)
            {
                _grid[column][row].Draw(spriteBatch, column, GridOrigin - row * Klax.Texture.Height);
            }
        }
        spriteBatch.End();
    }

    internal void Add(int column, Block block)
    {
        _grid[column].Add(block);

        //Search for matches
        do
        {
            ResetDeleteFlags();  
            SearchForMatches();  //Look for matches and mark their deleted flag
        } while (RemoveBlocks());  //If we removed any then iterate again as there may be new matches

    }

    public bool HasSpace(int column)
    {
        //Is there room in this column
        return _grid[column].Count < Klax.NumberOfRows;
    }
}

}

速聊1:
那是什么语言,请将其添加到标签中
速聊2:
抱歉.这一切都是新手.这是我第一次发帖.这是C#
速聊3:
我认为错误消息非常明显,soundEffectInstance为null.您可能要检查为什么soundEffect.CreateInstance()返回null,我相信(content.Load....)上方的行是原因.
速聊5:
我了解错误消息的含义.这意味着由于某种原因它没有将音频加载到实例中.我不知道是为什么它没有被加载.我已经查看并更改了在内容上可以想到的所有内容.我认为可能导致问题的加载行(原始代码中以及我现在正在使用.mp3的代码中的BTW不在源代码中)
解决过程1

根据您在代码中看到的内容,您正在使用Microsoft.Xna.Framework框架中的ContentManager.Load.

在这种假设下,您的代码可能永远无法工作,并且始终会返回null.

这里的问题是双重的:

  1. ContentManager.Load仅支持其定义所给定的特定类型(我将在下面发布一个链接).SoundEffects不属于这些类型

  2. 此加载方法认为所有给定的文件本身都没有扩展名,而是具有不给定的.xnb扩展名(并且具有xnb格式).

因此,您的Sounds / 24372 ^ pop2.mp3会转换为Sounds / 24372 ^ pop2.mp3.xnb.

直接来自文档的一个示例如何使用它:

Model model = contentManager.Load<Model>( ".\\content\\models\\box" );

这会将box.xnb加载为模型.

该方法的完整文档在这里:https : //msdn.microsoft.com/zh-cn/library/bb197848.aspx

就像我提到的那样,如果我假设您正在使用THAT方法是正确的,那么很清楚为什么加载失败,因为它正在寻找不存在的文件.但是,即使根据文档进行了纠正,它也仍然不起作用,因为它不是受支持的类型(尽管当您尝试使用该方法加载不受支持的方法但该方法不会引发异常时,我感到很奇怪.开发人员监督从根本上讲与您的问题无关).

I am trying to insert a sound whenever there is a match in my game. However, I keep getting a NullReferenceException when I get the match. It goes to the line soundEffectInstance.Play();. Any help is greatly appreciated. I've attempted everything when trying to get it to work. Here is my code:

using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;

namespace AndyKlax.KlaxGame
{
internal class Grid
{
    private const int GridOrigin = 660;


    SoundEffect soundEffect;
    SoundEffectInstance soundEffectInstance;


    private readonly List<Block>[] _grid = new List<Block>[Klax.NumberOfColumns];

    public void LoadContent(ContentManager content)
    {

        soundEffect = content.Load<SoundEffect>(@"Sounds/24372^pop2.mp3");
        soundEffectInstance = soundEffect.CreateInstance();

    }

    internal Grid()
    {
        for (int i = 0; i < Klax.NumberOfColumns; i++ )
        {
            _grid[i] = new List<Block>();
        }
    }

    private bool RemoveBlocks()
    {
        var foundBlocksToRemove = false;

        //Mark all blocks in the grid as unmatched
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row =_grid[column].Count -1 ; row >=0 ; row--) //Loop backwards do its safe to remove
            {
                if (_grid[column][row].Delete)
                {
                    _grid[column].RemoveAt(row);
                    foundBlocksToRemove = true;
                }
            }
        }

        return foundBlocksToRemove;
    }



    private void SearchForMatches()
    {

        //Search the whole grid - look for matches in each direction and set the deleted flag for anything you find
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row = 0; row < _grid[column].Count; row++)
            {
                SearchForMatches(column, row, 1, 0);  //Horizontal
                SearchForMatches(column, row, 0, 1);  //Vertical
                SearchForMatches(column, row, 1, 1);  //Diagonal one way
                SearchForMatches(column, row, 1, -1);  //Diagonal the other way
            }
        }
    }

    private void SearchForMatches(int column, int row, int xStep, int yStep)
    {


        int startColorIndex = _grid[column][row].ColorIndex;
        int matchCount = 0;

        int x = column;
        int y = row;

        //Loop in the given direction till we run out of color or grid
        do
        {
            matchCount++;
            x += xStep;
            y += yStep;

        } while (x < Klax.NumberOfColumns && y < _grid[x].Count && y>0 && startColorIndex == _grid[x][y].ColorIndex);

        //If the match is long enough 
        if (matchCount >= 3)
        {
            //Then mark all those blocks for removal
            x = column;
            y = row;

            //Loop in the given direction till we run out of color or grid
            do
            {
                _grid[x][y].Delete = true;

                x += xStep;
                y += yStep;
                soundEffectInstance.Play();

            } while (x < Klax.NumberOfColumns && y < _grid[x].Count && startColorIndex == _grid[x][y].ColorIndex);
        }
    }

    private void ResetDeleteFlags()
    {
        //Mark all blocks in the grid as unmatched
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row = 0; row < _grid[column].Count; row++)
            {
                _grid[column][row].Delete = false;
            }
        }
    }

    internal void Draw(SpriteBatch spriteBatch)
    {
        //Like the paddle the position of the block is inferred by its position in the grid
        spriteBatch.Begin();
        for (int column = 0; column < Klax.NumberOfColumns; column++)
        {
            for (int row = 0; row < _grid[column].Count; row++)
            {
                _grid[column][row].Draw(spriteBatch, column, GridOrigin - row * Klax.Texture.Height);
            }
        }
        spriteBatch.End();
    }

    internal void Add(int column, Block block)
    {
        _grid[column].Add(block);

        //Search for matches
        do
        {
            ResetDeleteFlags();  
            SearchForMatches();  //Look for matches and mark their deleted flag
        } while (RemoveBlocks());  //If we removed any then iterate again as there may be new matches

    }

    public bool HasSpace(int column)
    {
        //Is there room in this column
        return _grid[column].Count < Klax.NumberOfRows;
    }
}

}

Talk1:
What language is that, please add that to your tag
Talk2:
Sorry. New to all this. It's my first time posting. It's C#
Talk3:
I think the error message is quite obvious, soundEffectInstance is null. You might want to check why soundEffect.CreateInstance() is returning null, I believe the line above that (content.Load....) is the reason.
Talk5:
I understand what the error message means. It means that for some reason it is not loading the audio into the instance. What I can't figure out is why it's not being loaded. I've looked at and changed everything I can think of on the content.Load line that I thought might be causing the problem (BTW in my original code and in the code that I'm now using the .mp3 is not on the source)
Solutions1

From what I'm seeing in your code you are using ContentManager.Load from the Microsoft.Xna.Framework framework.

Under this assumption your code probably won't ever work and always will return null.

The problem here is twofold:

  1. ContentManager.Load supports only specific types as given by its definition (I'll post a link further below). SoundEffects are not part of these types

  2. This load method thinks that all files given have no extension by themselves but instead have an ungiven .xnb extension (and are of the xnb format).

Thus your Sounds/24372^pop2.mp3 translates to Sounds/24372^pop2.mp3.xnb for it.

One example directly from the documentation how it is used:

Model model = contentManager.Load<Model>( ".\\content\\models\\box" );

This would load box.xnb as a model.

The full documentation for that method is here: https://msdn.microsoft.com/en-us/library/bb197848.aspx

Like I mentioned if my assumption that you are using THAT method is correct then it is clear why the loading fails with that as it is looking for a file that does not exist. But even if that is corrected according to the documentation it should still not work as it is not of a supported type (I find it strange though that the method does not throw an exception when you try to use it to load something not supported but that developer oversight has nothing to do with your problem at all in essence).

转载于:https://stackoverflow.com/questions/28185992/null-reference-exception-being-given-when-trying-to-play-sound

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入