在Windows Phone上播放背景音频

时间:2013-03-10 16:40:48

标签: c# windows-phone-7 windows-runtime windows-phone

我想在Windows Phone的后台播放一些音频。我已经编写了一些像Microsoft(http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202978(v=vs.105).aspx)的示例代码,但在我的应用程序中,用户有机会选择后台代理必须播放的uri。但我不知道如何将我的app中的audiotrack元素设置为后台代理的audiotrack元素。

我在我的座席中尝试了以下代码:

private static AudioTrack _streamTrack;
public static AudioTrack StreamTrack { get { return _streamTrack; } set { _streamTrack = value; } }

并尝试在我的应用中设置此变量,如:

AudioPlayer.StreamTrack = new AudioTrack(new Uri(stream.StreamUri, UriKind.Absolute), stream.StreamName, stream.StreamGenre, stream.StreamGenre, null);

但它不起作用。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

实现此目的的一种方法是使用XNA库

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;

然后声明你的声音效果

SoundEffect _BGMUSIC;

我使用这种加载声音效果的方法

 //Put this in your main method
 LoadSound("sfx/piano.wav", out _BGMUSIC);


 //put this method in the same class
 private void LoadSound(String SoundFilePath, out SoundEffect Sound)
        {
            // For error checking, assume we'll fail to load the file.
            Sound = null;

            try
            {
                // Holds informations about a file stream.
                StreamResourceInfo SoundFileInfo = App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));

                // Create the SoundEffect from the Stream
                Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
                FrameworkDispatcher.Update();
            }
            catch (NullReferenceException)
            {
                // Display an error message
                MessageBox.Show("Couldn't load sound " + SoundFilePath);
            }
        }

最后你可以发挥你的音效

 _BGMUSIC.Play();

答案 1 :(得分:0)

您应该只将网址设置为BackgroundAudioPlayer.Instance.Track。

Source code

XAML

<StackPanel Orientation="Vertical">
  <TextBlock HorizontalAlignment="Center"
             VerticalAlignment="Center"
             Text="Enter url into textbox" />
  <TextBox Name="fileUrl" />
  <Button Content="&gt;"
          Height="100"
          Width="100"
          Click="playCustomFile_Click" />
</StackPanel>

CS

private void playCustomFile_Click(object sender, RoutedEventArgs e)
{
  if (string.IsNullOrEmpty(fileUrl.Text.Trim().ToString()))
     MessageBox.Show("Please enter url first");
  else
     BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri(fileUrl.Text.Trim().ToString(), UriKind.Absolute), "title","artist","album", new Uri("albumArtUrl",UriKind.RelativeOrAbsolute));
}
相关问题