C# System.InvalidOperationException错误

C# System.InvalidOperationException错误,c#,wpf,xaml,windows-phone-8,C#,Wpf,Xaml,Windows Phone 8,我正在尝试制作一个带有录音功能的音板应用程序,但我遇到了一个System.InvalidOperationException,当我单击“录音”时,由于某种原因,我的声音无法播放 Animals.xaml: <phone:PhoneApplicationPage x:Class="SoundBoard.Animals" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="

我正在尝试制作一个带有录音功能的音板应用程序,但我遇到了一个System.InvalidOperationException,当我单击“录音”时,由于某种原因,我的声音无法播放

Animals.xaml:

<phone:PhoneApplicationPage
    x:Class="SoundBoard.Animals"
    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"
    mc:Ignorable="d"
    d:DataContext="{d:DesignData SampleData/SampleData.xaml}"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait"  Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <phone:PhoneApplicationPage.Resources>
        <Storyboard x:Name="RotateCirlce" RepeatBehavior="Forever">
            <DoubleAnimation
                Duration="0:0:4"
                To="360"
                Storyboard.TargetProperty="(UIElement.RenderTransfrom).(CompositeTransform.Rotation)"
                Storyboard.TargetName="ReelGrid"
                d:IsOptimized="True" />

        </Storyboard>


    </phone:PhoneApplicationPage.Resources>

    <!--LayoutRoot contains the root grid where all other page content is placed-->
    <Grid x:Name="LayoutRoot">
        <phone:Panorama Title="{Binding Path=LocalizedResources.ApplicationTitle,
            Source={StaticResource LocalizedStrings}}">

            <!--Panorama item one-->
            <phone:PanoramaItem Header="Animals">
                <Grid>
                    <Image HorizontalAlignment="Left" Height="463" Margin="10,10,0,0" VerticalAlignment="Top" Width="400" Source="/Assets/cat.jpg"/>
                </Grid>
            </phone:PanoramaItem>

            <!--Panorama item two-->
            <phone:PanoramaItem Header="Sounds">
                <phone:LongListSelector
                    Margin="0,0,-12,0" 
                    ItemsSource="{Binding Animals.Items}"
                    LayoutMode="Grid"
                    GridCellSize="150,150"                  
                    >
                    <phone:LongListSelector.ItemTemplate>
                        <DataTemplate>
                            <Grid Background="{StaticResource PhoneAccentBrush}">

                                <Grid VerticalAlignment="Top" HorizontalAlignment="Right" 
                                      Width="40" Height="40" Margin="0,6,6,0">
                                    <Ellipse Stroke="{StaticResource PhoneForegroundBrush}" 
                                             StrokeThickness="3" />
                                    <Image Source="Assets/AppBar/Play.png" />


                                </Grid>

                                <StackPanel VerticalAlignment="Bottom">
                                    <TextBlock Text="{Binding Title}"
                                               Margin="6,0,0,6"/>

                                </StackPanel>

                            </Grid>

                        </DataTemplate>
                    </phone:LongListSelector.ItemTemplate>
                </phone:LongListSelector>
            </phone:PanoramaItem>

            <!--Panorama item three-->
            <phone:PanoramaItem Header="Record">
                <Grid>
                    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
                        <MediaElement x:Name="AudioPlayer" AutoPlay="False" />

                        <StackPanel>
                            <ToggleButton Content="Record"
                                          Checked="RecordAudioChecked"
                                          Unchecked="RecordAudioUnchecked"/>
                            <Grid Width="200" 
                                  Height="200" 
                                  Name="ReelGrid"
                                  RenderTransformOrigin=".5,.5">
                                <Grid.RenderTransform>
                                    <CompositeTransform />
                                </Grid.RenderTransform>


                                <Ellipse Fill="{StaticResource PhoneAccentBrush}" />

                                <Ellipse Height="20"
                                         Width="20"
                                         Fill="{StaticResource PhoneForegroundBrush}" />
                                <Rectangle Height="20"
                                           Width="20"
                                           Margin="0,20,0,20"
                                           VerticalAlignment="Top" 
                                           Fill="{StaticResource PhoneForegroundBrush}" />

                                <Rectangle Height="20"
                                           Width="20"
                                           Margin="0,20,0,20"
                                           VerticalAlignment="Bottom" 
                                           Fill="{StaticResource PhoneForegroundBrush}" />

                                <Rectangle Height="20"
                                           Width="20"
                                           Margin="0,0,20,0"
                                           HorizontalAlignment="Right" 
                                           Fill="{StaticResource PhoneForegroundBrush}" />

                                <Rectangle Height="20"
                                           Width="20"
                                           Margin="20,0,0,0"
                                           HorizontalAlignment="Left" 
                                           Fill="{StaticResource PhoneForegroundBrush}" />

                            </Grid>
                            <Button Name="PlayAudio" Content="Play" Click="PlayAudioClick" />
                        </StackPanel>
                    </Grid>
                </Grid>
            </phone:PanoramaItem>

        </phone:Panorama>
    </Grid>

</phone:PhoneApplicationPage>

和anists.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SoundBoard.Resources;
using Coding4Fun.Toolkit.Audio;
using Coding4Fun.Toolkit.Audio.Helpers;
using System.IO;
using System.IO.IsolatedStorage;
using Coding4Fun.Toolkit.Controls;
using SoundBoard.ViewModels;
using Newtonsoft.Json;
using System.Windows.Media.Animation;

namespace SoundBoard
{
    public partial class Animals : PhoneApplicationPage
    {
        private MicrophoneRecorder _recorder = new MicrophoneRecorder();
        private IsolatedStorageFileStream _audioStream;
        private string _tempFileName = "tempWav.wav";


        public Animals()
        {
            InitializeComponent();

            DataContext = App.ViewModel;

            BuildLocalizedApplicationBar();
        }
        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LongListSelector selector = sender as LongListSelector;

            // verifying our sender is actually a LongListSelector
            if (selector == null)
                return;

            SoundData data = selector.SelectedItem as SoundData;

            // verifying our sender is actually SoundData
            if (data == null)
                return;

            if (File.Exists(data.FilePath))
            {
                AudioPlayer.Source = new Uri(data.FilePath, UriKind.RelativeOrAbsolute);
            }
            else
            {
                using (var storageFolder = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var stream = new IsolatedStorageFileStream(data.FilePath, FileMode.Open, storageFolder))
                    {
                        AudioPlayer.SetSource(stream);
                    }
                }
            }

            selector.SelectedItem = null;
        }

        private void BuildLocalizedApplicationBar()
        {
            ApplicationBar = new ApplicationBar();

            ApplicationBarIconButton recordAudioAppBar =
                new ApplicationBarIconButton();

            recordAudioAppBar.IconUri = new Uri("/Assets/AppBar/Save.png", UriKind.Relative);
            recordAudioAppBar.Text = AppResources.AppBarSave;

            recordAudioAppBar.Click += recordAudioAppBar_Click;

            ApplicationBar.Buttons.Add(recordAudioAppBar);
            ApplicationBar.IsVisible = false;

        }

        void recordAudioAppBar_Click(object sender, EventArgs e)
        {
            InputPrompt fileName = new InputPrompt();

            fileName.Message = "What should we call the sound?";

            fileName.Completed += FileNameCompleted;

            fileName.Show();

        }

        private void FileNameCompleted(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            if (e.PopUpResult == PopUpResult.Ok)
            {

                // Create a sound data object

                SoundData soundData = new SoundData();
                soundData.FilePath = string.Format("/customAudio/{0}.wav", DateTime.Now.ToFileTime());
                soundData.Title = e.Result;

                // Save the wav file into the DIR /customAudio/

                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!isoStore.DirectoryExists("/customAudio/"))
                        isoStore.CreateDirectory("/customAudio/");

                    isoStore.MoveFile(_tempFileName, soundData.FilePath);
                }


                // Add the SoundData to App.ViewModel.CustomSounds

                App.ViewModel.CustomSounds.Items.Add(soundData);

                // Save the list of CustomSounds to isolatedStorage.ApplicationSettings

                var data = JsonConvert.SerializeObject(App.ViewModel.CustomSounds);

                IsolatedStorageSettings.ApplicationSettings[SoundModel.CustomSoundKey] = data;
                IsolatedStorageSettings.ApplicationSettings.Save();

                // We'll need to modify sound model to retrieve CustomSounds
                //from isolatedStorage.ApplicationSettings

                NavigationService.Navigate(new Uri("", UriKind.RelativeOrAbsolute));
            }
        }

        private void RecordAudioChecked(object sender, RoutedEventArgs e)
        {
            PlayAudio.IsEnabled = false;
            ApplicationBar.IsVisible = false;
            RotateCirlce.Begin();
            _recorder.Start();
        }

        private void RecordAudioUnchecked(object sender, RoutedEventArgs e)
        {
            _recorder.Stop();

            SaveTempAudio(_recorder.Buffer);

            RotateCirlce.Stop();
            PlayAudio.IsEnabled = true;
            ApplicationBar.IsVisible = true;

        }

        private void SaveTempAudio(MemoryStream buffer)
        {
            //defensive...
            if (buffer == null)
                throw new ArgumentNullException("Attempting a save on empty sound buffer.");

            //Clean out hold on audioStream
            if (_audioStream != null)
            {
                AudioPlayer.Stop();
                AudioPlayer.Source = null;

                _audioStream.Dispose();
            }

            var bytes = buffer.GetWavAsByteArray(_recorder.SampleRate);

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {

                if (isoStore.FileExists(_tempFileName))
                    isoStore.DeleteFile(_tempFileName);

                _tempFileName = string.Format("{0}.wav", DateTime.Now.ToFileTime());


                _audioStream = isoStore.CreateFile(_tempFileName);
                _audioStream.Write(bytes, 0, bytes.Length);
                //Play ...  SetSource of a mediaElement
                AudioPlayer.SetSource(_audioStream);

            }

        }

        private void PlayAudioClick(object sender, RoutedEventArgs e)
        {
            AudioPlayer.Play();
        }

    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
Net系统;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Media;
使用System.Windows.Navigation;
使用System.Windows.Resources;
使用Microsoft.Phone.Controls;
使用Microsoft.Phone.Shell;
使用音板资源;
使用Coding4Fun.Toolkit.Audio;
使用Coding4Fun.Toolkit.Audio.Helpers;
使用System.IO;
使用System.IO.IsolatedStorage;
使用Coding4Fun.Toolkit.Controls;
使用SoundBoard.ViewModels;
使用Newtonsoft.Json;
使用System.Windows.Media.Animation;
名称空间音板
{
公共部分类动物:PhoneApplicationPage
{
专用麦克风记事本_recorder=新麦克风记事本();
私有隔离存储文件流(audioStream);
私有字符串_tempFileName=“tempWav.wav”;
公共动物()
{
初始化组件();
DataContext=App.ViewModel;
BuildLocalizedApplicationBar();
}
//加载ViewModel项的数据
受保护的覆盖无效OnNavigatedTo(NavigationEventArgs e)
{
如果(!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
私有void LongListSelector_SelectionChanged(对象发送方,SelectionChangedEventArgs e)
{
LongListSelector=发送方作为LongListSelector;
//验证我们的发件人实际上是一个长列表选择器
if(选择器==null)
返回;
SoundData data=selector.SelectedItem作为SoundData;
//验证我们的发送者实际上是可靠的数据
如果(数据==null)
返回;
if(File.Exists(data.FilePath))
{
AudioPlayer.Source=新Uri(data.FilePath,UriKind.RelativeOrAbsolute);
}
其他的
{
使用(var storageFolder=IsolatedStorageFile.GetUserStoreForApplication())
{
使用(var stream=new-IsolatedStorageFileStream(data.FilePath,FileMode.Open,storageFolder))
{
AudioPlayer.SetSource(流);
}
}
}
selector.SelectedItem=null;
}
私有void BuildLocalizedApplicationBar()
{
ApplicationBar=新的ApplicationBar();
ApplicationBarIconButton录制音频应用程序栏=
新应用程序BariconButton();
recordAudioAppBar.IconUri=新Uri(“/Assets/AppBar/Save.png”,UriKind.Relative);
recordAudioAppBar.Text=AppResources.AppBarSave;
recordAudioAppBar.单击+=recordAudioAppBar\u单击;
ApplicationBar.Buttons.Add(recordAudioAppBar);
ApplicationBar.IsVisible=false;
}
void recordAudioAppBar_单击(对象发送者,事件参数e)
{
InputPrompt文件名=新的InputPrompt();
fileName.Message=“我们应该如何称呼声音?”;
fileName.Completed+=FileNameCompleted;
fileName.Show();
}
私有无效文件名已完成(对象发送方,PopUpEventArgs e)
{
如果(e.PopUpResult==PopUpResult.Ok)
{
//创建声音数据对象
SoundData SoundData=新的SoundData();
soundData.FilePath=string.Format(“/customAudio/{0}.wav”,DateTime.Now.ToFileTime());
soundData.Title=e.结果;
//将wav文件保存到DIR/customAudio中/
使用(IsolatedStorageFile isoStore=IsolatedStorageFile.GetUserStoreForApplication())
{
如果(!isoStore.directory存在(“/customAudio/”)
创建目录(“/customAudio/”);
isoStore.MoveFile(_tempFileName,soundData.FilePath);
}
//将声音数据添加到App.ViewModel.CustomSounds
App.ViewModel.CustomSounds.Items.Add(soundData);
//将CustomSounds列表保存到isolatedStorage.ApplicationSettings
var data=JsonConvert.SerializeObject(App.ViewModel.CustomSounds);
IsolatedStorageSettings.ApplicationSettings[SoundModel.CustomSoundKey]=数据;
IsolatedStorageSettings.ApplicationSettings.Save();