2013-03-10 206 views
2

我想在Windows Phone的背景中播放一些音頻。我已經寫了一些像微軟這樣的代碼(http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202978(v=vs.105).aspx),但在我的應用程序中,用戶有機會選擇後臺代理必須玩的uri。但我不知道如何將我的應用中的audiotrack元素設置爲後臺代理的audiotrack元素。在Windows Phone上播放背景音頻

我試過下面的代碼在我的經紀人:

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); 

但它不工作。我該如何解決這個問題?要做到這一點

+0

如果下面的答案固定您的問題請務必勾選並給予好評。如果不是,請提供評論爲什麼它不起作用。謝謝 – 2013-12-16 20:36:27

回答

0

一種方法是使用XNA庫

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

然後宣佈你SoundEffect中

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