发生了'System.NullReferenceException'类型的异常,我没有ideia如何处理

时间:2014-04-10 18:57:32

标签: c#

点击我的XAML上的“播放”按钮后出现问题,然后我的应用程序崩溃,返回此错误:

“PhoneApp1.DLL中出现'System.NullReferenceException'类型的第一次机会异常 PhoneApp1.DLL中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理 附加信息:对象引用未设置为对象的实例。“

我的XAML.CS代码是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Silverlight.Media;


namespace PhoneApp1
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Quando sair da página, o ShoutcastMediaStreamSource será retirado (disposed).")]
    public partial class MainPage : PhoneApplicationPage
    {
        /// <summary>
        /// Representa um sream do Shoutcast
        /// </summary>
        private ShoutcastMediaStreamSource source;

        /// <summary>
        /// Interrompe a atualização do status caso algum erro ocorra
        /// </summary>
        private bool errorOccured;

        /// <summary>
        /// Obtem o elemento Media da página
        /// </summary>
        private MediaElement MediaPlayer
        {
            get { return this.Resources["mediaPlayer"] as MediaElement; }
        }

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

        private void MediaElement_BufferingProgressChanged(object sender, RoutedEventArgs e)
        {
            UpdateStatus();
        }

        private void MediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            errorOccured = true;
            txtStatus.Text = string.Format(CultureInfo.InvariantCulture, "Erro: {0}", e.ErrorException.Message);
        }

        private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            UpdateStatus();
        }

        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            if (MediaPlayer.CurrentState != MediaElementState.Paused)
            {
                ResetMediaPlayer();

                Uri uri = new Uri("http://neko-radio.com:8000/radio"); //Ajuste de acordo com sua necessidade
                source = new ShoutcastMediaStreamSource(uri);
                source.MetadataChanged += source_MetadataChanged;
                MediaPlayer.SetSource(source);
            }
            MediaPlayer.Play();
            pbCarregando.IsIndeterminate = true;
        }

        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            if (MediaPlayer.CurrentState == MediaElementState.Playing || MediaPlayer.CurrentState == MediaElementState.Opening || MediaPlayer.CurrentState == MediaElementState.Buffering)
                MediaPlayer.Pause();
        }

        void source_MetadataChanged(object sender, RoutedEventArgs e)
        {
            UpdateStatus();
        }

        private void UpdateStatus()
        {
            if (errorOccured)
                return;
            else
            {
                MediaElementState state = MediaPlayer.CurrentState;
                string status = string.Empty;

                switch (state)
                {
                    case MediaElementState.Buffering:
                        status = string.Format(CultureInfo.InvariantCulture, "Buffering...{0:0%}", this.MediaPlayer.BufferingProgress);
                        break;
                    case MediaElementState.Playing:
                        status = string.Format(CultureInfo.InvariantCulture, "Title: {0}", this.source.CurrentMetadata.Title);
                        if (status.Trim() != "Titulo:")
                            pbCarregando.IsIndeterminate = false;
                        break;
                    default:
                        status = state.ToString();
                        break;
                }

                txtStatus.Text = status;
            }
        }

        private void ResetMediaPlayer()
        {
            if ((this.MediaPlayer.CurrentState != MediaElementState.Stopped) && (this.MediaPlayer.CurrentState != MediaElementState.Closed))
            {
                this.MediaPlayer.Stop();
                this.MediaPlayer.Source = mediaPlayer.Source;
                this.source.Dispose();
                this.source = source;
            }

            this.errorOccured = false;
        }

        private void PageUnloaded(object sender, EventArgs e)
        {
            ResetMediaPlayer();
        }
    }
}

编辑:

我的XAML

<phone:PhoneApplicationPage
    x:Class="PhoneApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="#FF00B2CA">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="App" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock Text="Toca Rádio" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Image x:Name="imgAng" Source="/Assets/Ang.jpg" Margin="20,59,0,138"/>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="56,495,33,31">
                <Button Name="btnPlay" Content="Play" Click="btnPlay_Click" Width="150" />
                <Button x:Name="btnPause" Content="Pause" Click="btnPause_Click" Width="150" />
            </StackPanel>

            <MediaElement x:Name="mediaPlayer" AutoPlay="True" Volume="1.0" BufferingProgressChanged="MediaElement_BufferingProgressChanged"
            MediaFailed="MediaElement_MediaFailed" CurrentStateChanged="MediaElement_CurrentStateChanged" Margin="56,125,33,226" />
            <ProgressBar x:Name="pbCarregando" HorizontalAlignment="Left" Height="38" Margin="56,457,0,0" VerticalAlignment="Top" Width="376" IsIndeterminate="false"/>
            <TextBlock x:Name="txtStatus" HorizontalAlignment="Left" Margin="56,400,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="64" Width="181"/>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

0 个答案:

没有答案