System.InvalidOperationException错误

时间:2014-03-19 23:38:46

标签: 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="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>

和Animals.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();
        }

    }
}

干杯球员

1 个答案:

答案 0 :(得分:0)

所以这是来自channel9的绝对初学者视频。可以在https://absolutebeginner.codeplex.com/

找到所有样本的完整来源

首先,我验证您是否设置了麦克风功能标志。接下来,我将您的代码与该课程中的示例代码进行比较。