2012-01-17 4 views
0

6.5.1 가이드 라인으로 인해 내 앱이 인증에 실패했습니다. "애플리케이션이 사용자의 음악을 일시 중지하는 상태에 도달 할 수 있습니다."MediaPlayer.GameHasControl이 제대로 작동하지 않습니다.

나는이 문제에 대한 해결책을 찾았으며 사용자가 응용 프로그램을 시작하기 전에 음악 재생 여부를 확인하기 위해 MediaPlayer.GameHasControl을 사용해야한다는 것을 알았습니다.

구현했을 때 작동하지 않았습니다. 그것은 음악을 일시 중지하는 것에 대해 즉흥적 이었지만 반응하기 전에 일시 중지했습니다. OnNavigatedTo(), Loaded() 및 생성자에 MediaPlayer.GameHasControl을 넣으려고 시도했지만 잠시 동안 작동하지만 앱이 몇 초 후에 충돌하기 때문에 옵션이 아닙니다. 그런 다음 MediaEpenments 이벤트를 3 개의 MediaElements에서 처리했지만 운이 없었습니다. 이제 막 막혔다. 누군가가 이것에 대해 밝힐 수 있다면, 나는 매우 감사 할 것입니다. 나는 내가 집에 도착 후 지시를 수행하는 데 사용하는 코드이 대답을 업데이트합니다

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.Shapes; 
using Microsoft.Phone.Controls; 
using System.Xml.Linq; 
using System.Windows.Navigation; 
using System.Windows.Media.Imaging; 
using Microsoft.Xna.Framework.Media; 
using Microsoft.Xna.Framework; 

namespace RhythmCoach 
{ 
    public partial class BeginnerExercisePage : PhoneApplicationPage 
    { 
    public BeginnerExercisePage() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnNavigatedTo(NavigationEventArgs e) 
    { 
     XDocument beginnerExerciseData = XDocument.Load("XML/BeginnerXML.xml"); 

     string name = string.Empty; 

     if (NavigationContext.QueryString.TryGetValue("name", out name)) 
     { 

      var exercise = (from Exercised in beginnerExerciseData.Descendants("Exercised") 
          where Exercised.Attribute("name").Value == name 
          select new Exercise 
          { 
           ExImage = (string)Exercised.Element("image").Value, 
           ExGuitarAudio = (string)Exercised.Element("GuitarAudio").Value, 
           ExPianoAudio = (string)Exercised.Element("PianoAudio").Value, 
           ExSnareAudio = (string)Exercised.Element("SnareAudio").Value, 
           ExTitle = (string)Exercised.Element("title").Value 
          }).Single(); 

      im.Source = new BitmapImage(new Uri(exercise.ExImage, UriKind.Relative)); 
      pageTitle.Text = exercise.ExTitle; 

      guitarAudioPlayer.Source = new Uri(exercise.ExGuitarAudio,UriKind.Relative); 
      pianoAudioPlayer.Source = new Uri(exercise.ExPianoAudio, UriKind.Relative); 
      snareAudioPlayer.Source = new Uri(exercise.ExSnareAudio, UriKind.Relative); 
     } 

     rbBegSnare.IsChecked = true; 
     base.OnNavigatedTo(e); 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     if (rbBegGuitar.IsChecked == true) 
     { 
      guitarAudioPlayer.Play(); 

     } 
     else if (rbBegPiano.IsChecked == true) 
     { 
      pianoAudioPlayer.Play(); 

     } 
     else 
      snareAudioPlayer.Play(); 

    } 

    private void button2_Click(object sender, RoutedEventArgs e) 
    { 
     if (rbBegGuitar.IsChecked == true) 
     { 
      guitarAudioPlayer.Stop(); 
      pianoAudioPlayer.Stop(); 
      snareAudioPlayer.Stop(); 
     } 
     else if (rbBegPiano.IsChecked == true) 
     { 
      pianoAudioPlayer.Stop(); 
      guitarAudioPlayer.Stop(); 
      snareAudioPlayer.Stop(); 
     } 
     else 
      snareAudioPlayer.Stop(); 
      guitarAudioPlayer.Stop(); 
      pianoAudioPlayer.Stop(); 
    } 

    private void button3_Click(object sender, RoutedEventArgs e) 
    { 
     if (rbBegGuitar.IsChecked == true) 
     { 
      guitarAudioPlayer.Pause(); 
      pianoAudioPlayer.Pause(); 
      snareAudioPlayer.Pause(); 
     } 
     else if (rbBegPiano.IsChecked == true) 
     { 
      pianoAudioPlayer.Pause(); 
      guitarAudioPlayer.Pause(); 
      snareAudioPlayer.Pause(); 
     } 
     else 
      snareAudioPlayer.Pause(); 
      guitarAudioPlayer.Pause(); 
      pianoAudioPlayer.Pause(); 
    } 

    private void rbBegGuitar_Checked(object sender, RoutedEventArgs e) 
    { 
     pianoAudioPlayer.Stop(); 
     snareAudioPlayer.Stop(); 
    } 

    private void rbBegPiano_Checked(object sender, RoutedEventArgs e) 
    { 
     guitarAudioPlayer.Stop(); 
     snareAudioPlayer.Stop(); 
    } 

    private void rbBegSnare_Checked(object sender, RoutedEventArgs e) 
    { 
     guitarAudioPlayer.Stop(); 
     pianoAudioPlayer.Stop(); 
    } 

    private void guitarAudioPlayer_MediaOpened(object sender, RoutedEventArgs e) 
    { 
     if (!MediaPlayer.GameHasControl) 
     { 
      MessageBoxResult Choice; 
      Choice = MessageBox.Show("Media is currently playing, do you want to stop it?", "Stop Player", MessageBoxButton.OKCancel); 
      if (Choice != MessageBoxResult.OK) 
      { 
       if (NavigationService.CanGoBack) 
        NavigationService.GoBack(); 
       else 
        NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative)); 
       return; 
      } 
     } 
    } 

    private void pianoAudioPlayer_MediaOpened(object sender, RoutedEventArgs e) 
    { 
     if (!MediaPlayer.GameHasControl) 
     { 
      MessageBoxResult Choice; 
      Choice = MessageBox.Show("Media is currently playing, do you want to stop it?", "Stop Player", MessageBoxButton.OKCancel); 
      if (Choice != MessageBoxResult.OK) 
      { 
       if (NavigationService.CanGoBack) 
        NavigationService.GoBack(); 
       else 
        NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative)); 
       return; 
      } 
     } 
    } 

    private void snareAudioPlayer_MediaOpened(object sender, RoutedEventArgs e) 
    { 
     if (!MediaPlayer.GameHasControl) 
     { 
      MessageBoxResult Choice; 
      Choice = MessageBox.Show("Media is currently playing, do you want to stop it?", "Stop Player", MessageBoxButton.OKCancel); 
      if (Choice != MessageBoxResult.OK) 
      { 
       if (NavigationService.CanGoBack) 
        NavigationService.GoBack(); 
       else 
        NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative)); 
       return; 
      } 
     } 
    } 
} 

}

및 XAML

<Grid x:Name="LayoutRoot"> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="242*" /> 
     <ColumnDefinition Width="243*" /> 
     <ColumnDefinition Width="243*" /> 
    </Grid.ColumnDefinitions> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition Height="163*"/> 
     <RowDefinition Height="245*" /> 
    </Grid.RowDefinitions> 

    <!--TitlePanel contains the name of the application and page title--> 
    <StackPanel x:Name="TitlePanel" Margin="12,17,0,28" Grid.ColumnSpan="3"> 
     <TextBlock x:Name="ApplicationTitle" Text="BEGINNER EXERCISES" Style="{StaticResource PhoneTextNormalStyle}" Foreground="Black" /> 
     <TextBlock x:Name="PageTitle" Text="{Binding ExTitle}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" Foreground="Black" /> 
    </StackPanel> 

    <!--ContentPanel - place additional content here--> 

     <Image x:Name="im" Grid.Row="1" Margin="12,0,12,155" Grid.RowSpan="2" Grid.ColumnSpan="3" /> 

    <Button Grid.Row="2" Height="72" HorizontalAlignment="Left" Margin="41,13,0,0" x:Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" BorderBrush="Black" Foreground="Black" ClickMode="Release"> 
     <Button.Background> 
      <ImageBrush ImageSource="/RhythmCoach;component/Images/appbar.transport.play.rest.png" Stretch="None" /> 
     </Button.Background> 
    </Button> 
    <MediaElement Grid.Row="2" Height="120" HorizontalAlignment="Left" Name="guitarAudioPlayer" VerticalAlignment="Top" Width="160" Source="{Binding ExGuitarAudio}" AutoPlay="False" Volume="100" MediaOpened="guitarAudioPlayer_MediaOpened" /> 
    <MediaElement Grid.Row="2" Height="120" HorizontalAlignment="Left" Name="pianoAudioPlayer" VerticalAlignment="Top" Width="160" Source="{Binding ExPianoAudio}" AutoPlay="False" Volume="100" MediaOpened="pianoAudioPlayer_MediaOpened" /> 
    <MediaElement Grid.Row="2" Height="120" HorizontalAlignment="Left" Name="snareAudioPlayer" VerticalAlignment="Top" Width="160" Source="{Binding ExSnareAudio}" AutoPlay="False" Volume="100" MediaOpened="snareAudioPlayer_MediaOpened" /> 
    <Button Grid.Row="2" Height="72" HorizontalAlignment="Left" Margin="41,13,0,0" Name="button2" VerticalAlignment="Top" Width="160" Click="button2_Click" Grid.Column="2" BorderBrush="Black" Foreground="Black" HorizontalContentAlignment="Center"> 
     <Button.Background> 
      <ImageBrush ImageSource="/RhythmCoach;component/Images/appbar.transport.stop.rest1.png" Stretch="None" /> 
     </Button.Background> 
    </Button> 
    <Button Grid.Column="1" Grid.Row="2" Height="72" HorizontalAlignment="Left" Margin="41,13,0,0" Name="button3" VerticalAlignment="Top" Width="160" Click="button3_Click" Foreground="Black" BorderBrush="Black"> 
     <Button.Background> 
      <ImageBrush ImageSource="/RhythmCoach;component/Images/appbar.transport.pause.rest.png" Stretch="None" /> 
     </Button.Background> 
    </Button> 
    <RadioButton Content="Guitar" Grid.Row="2" Height="72" HorizontalAlignment="Left" Margin="41,101,0,0" Name="rbBegGuitar" VerticalAlignment="Top" Foreground="Black" Background="#BFADADAD" BorderBrush="#BFFFFFFF" Checked="rbBegGuitar_Checked" /> 
    <RadioButton Content="Piano" Grid.Column="1" Grid.Row="2" Height="72" HorizontalAlignment="Left" Margin="41,101,0,0" Name="rbBegPiano" VerticalAlignment="Top" Background="#BFA3A3A3" Foreground="Black" Checked="rbBegPiano_Checked" /> 
    <RadioButton Content="Snare Drum" Grid.Column="2" Grid.Row="2" Height="72" HorizontalAlignment="Left" Margin="32,101,0,0" Name="rbBegSnare" VerticalAlignment="Top" Background="#BF939393" Foreground="Black" Checked="rbBegSnare_Checked" /> 
    <my:AdControl AdUnitId="10029089" ApplicationId="05ab3750-df60-4e42-9939-ab68de9f424b" Height="50" HorizontalAlignment="Left" Margin="186,17,0,0" Name="adControlSmall" VerticalAlignment="Top" Width="300" Grid.ColumnSpan="2" Grid.Column="1" /> 
    <Grid.Background> 
     <ImageBrush ImageSource="/RhythmCoach;component/Images/bg1.png" Stretch="Fill" /> 
    </Grid.Background> 
</Grid> 

답변

1

:

여기에 코드입니다. 나는 나의 것이 Loaded()에 있다고 생각한다. mediaElements가 자동 실행으로 설정되어 있지 않아서 문제가되어서는 안됩니다. 메시지를 모두 제거하면 페이지의 아무 버튼도 누르지 않아도 배경 음악이 일시 중지됩니까?

다른 사람들이 처리하는 또 다른 방법은 응용 프로그램을 실행할 때 항상 묻는 메시지를 표시하는 대신 응용 프로그램을 실행할 때 항상 배경 음악을 일시 중지할지 여부를 묻는 것입니다. 해당 설정을 저장 한 다음 후속 실행에서 확인하십시오. 기본 메뉴가있는 것처럼 보이므로 배경 음악을 일시 중지하기로 동의하지 않으면 음악이있는 페이지로 이동하지 못하게 될 수 있습니다. ,

protected override void OnNavigatedTo(NavigationEventArgs e) 
{ 
    base.OnNavigatedTo(e); 
    //remember don't show MessageBoxes in OnNavigatedTo.. 
    // better to move stuff over to Loaded as much as you can anyway 
    this.Loaded += RunOnPageLoaded; //you could hook up to this event via the Designer too 
} 

void RunOnPageLoaded(object sender, RoutedEventArgs e) 
{ 
    bool doLoad = true; 
    FrameworkDispatcher.Update(); 
    if (!MediaPlayer.GameHasControl) 
    { 
     doLoad = PromptUserAboutBackgroundMusic(); 
     if (doLoad) MediaPlayer.Pause(); 
    } 

    if (doLoad) 
    { 
     LoadMediaFiles(); 
    } 
} 

private bool PromptUserAboutBackgroundMusic() 
{ 
    var result = MessageBox.Show("Do you want to stop your background music to play this recording?", 
           "Stop music?", MessageBoxButton.OKCancel); 
    if (result == MessageBoxResult.OK) return true; 
    return false; 
} 

private void LoadMediaFiles() 
{ 
    //load your media files into your mediaelements here 
    //mediaElement.AutoPlay = true; 
    //mediaElement.Source = ... 
} 

이 당신이 요구 한 일이 될 수 있지만 :

나는 내 코드를 붙여 넣으려고하지만 조금 난 당신이 후있어 고기를 추출한 혼란되었을 수 있습니다 당신이하고있는 것을보고 난 후에 MediaElements가 당신이 사용하는 것이 가장 좋은 것인지 잘 모르겠습니다. 대신 SoundEffectInstance를 사용했다면 배경 음악이 일시 정지되지 않고 그 기능을 추가하기 전까지는 배경 음악에 관한 메시지를 귀찮게하지 않아도됩니다.

+0

답변 해 주셔서 감사합니다. 네, 프롬프트없이 멈 춥니 다. 나중에 코드를 게시 해 주셔서 감사합니다! 다행히도이 문제를 해결하는 데 도움이되기를 바랍니다. –

+0

대단히 감사합니다! 위의 코드는 그것을 해결했습니다! 이제 작동하고 충돌하지 않습니다. –

+0

이제 잠깐 테스트 해 보니 프롬프트가 다시 깨지는 것 같습니다. 프롬프트를 4 ~ 5 초 정도 열어두면 앱이 종료됩니다. 그곳에 있어야할까요? 그것 이외에 그것은 잘 작동합니다. –

0

MediaPlayer.GameHasControl을 호출하기 전에 FrameworkDispatcher.Update();를 호출 할 수 있습니다. 예외로 인해 앱 충돌이 발생하지 않도록하는 데 도움이됩니다.

+0

답장을 보내 주셔서 감사합니다. OnNavigatedTo()에서 시도했지만 여전히 충돌했습니다. 충돌로 인해 5 초 정도 지나면 앱을 종료했다는 의미입니다. –

+0

그냥 OnNavigatedTo()에서 볼 수있는 다른 모양을 지정하면 rbBegSnare.IsChecked = true; 그런 다음 일부 MediaElements에서 .Stop()을 호출합니다. 이 줄을 주석으로 처리하고 여전히 음악을 일시 중지했는지 확인하십시오. 그것이 고칠 경우 예를 들어 플래그로 할 수있는 일이 있습니다. –

+1

Heh 위의 잘못된 설명에 댓글을 달았습니다. 어쨌든이 스레드에 대한 주석 : OnNavigatedTo의 충돌은 Messagebox 프롬프트가있을 때 발생했을 수 있습니다 .. 그렇게 할 경우 X 초 내에 버튼을 클릭하지 않으면 탐색이 생각되므로 앱이 종료됩니다. 실패한. –

1
public MainPage() 
    { 
     InitializeComponent(); 

     bool canPlayMusic = true; 

     FrameworkDispatcher.Update(); 

     if (!MediaPlayer.GameHasControl) 
     { 
      if (MessageBox.Show("Is it ok to stop currently playing music?", 
       "Can stop music?", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) 
      { 
       canPlayMusic = false; 
      } 
     } 

     if (canPlayMusic) 
     { 
      MediaPlayer.Pause(); 

      runBackgroundMusic(); 
     } 
    } 
+0

음악 플레이어를 일시 중지합니다. 하지만 음악 플레이어를 닫고 싶습니다. 일단 일시 중지되면 사용자가 볼륨을 높이려고하면 음악의 일시 중지 상태가 표시되기 때문입니다. 따라서 사용자는 노래를 다시 재생할 수 있습니다. 그래서 사용자가 확인을 누르면 음악 플레이어를 닫고 싶습니다. 어떻게 그럴 수 있습니까? ????? – SaravanaKumar

관련 문제