2012-04-06 164 views
0

我有很多的.wav文件的播放,並因爲我創建AudioItem類:Windows Phone的聲音播放

public class AudioItem 
{ 
    public string SongName { get; set; } 
    public string SongText { get; set; } 

    public AudioItem() 
    { } 

    /// <summary> 
    /// Initialize AudioItem class 
    /// </summary> 
    /// <param name="SongName">The name of the song(with .wav)</param> 
    /// <param name="SongText">Text to display</param> 
    public AudioItem(string SongName, string SongText) 
    { 
     this.SongName = SongName; 
     this.SongText = SongText; 
    } 

    public void Play() 
    { 
     var stream = TitleContainer.OpenStream("Sound/" + SongName); 
     var effect = SoundEffect.FromStream(stream); 
     FrameworkDispatcher.Update(); 
     effect.Play(); 
    } 

} 

在視圖中我有一個項目Listbox

<ListBox Name="soundtrackLbx"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <Button Name="ListButton" HorizontalAlignment="Stretch" > 
          <Button.Content> 
           <StackPanel Orientation="Horizontal"> 
            <Image Margin="10" Height="30" Width="30" Source="Picture/audio.png"/> 
            <TextBlock Margin="10" HorizontalAlignment="Stretch" Text="{Binding SongText}" FontFamily="Verdana" Tap="TextBlock_Tap" /> 
           </StackPanel> 
          </Button.Content> 
         </Button> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 

我代碼背後:

public ObservableCollection<AudioItem> AudioItems { get; set; } 

    public MainView() 
    { 
     InitializeComponent(); 
     AudioItems = new ObservableCollection<AudioItem>(); 

     Initialize(); 
     this.soundtrackLbx.ItemsSource = AudioItems; 
    } 

    private void Initialize() 
    { 
     AudioItems.Add(new AudioItem("ApsolutnoDa.wav", "Apsolutno da")); 
     AudioItems.Add(new AudioItem("Da.wav", "Da")); 

    } 

    private void TextBlock_Tap(object sender, GestureEventArgs e) 
    { 
     TextBlock tblock = sender as TextBlock; 
     string text = tblock.Text; 

     AudioItem item = AudioItems.SingleOrDefault(a => a.SongText == text); 
     item.Play(); 
    } 

好吧,碰巧.wav有時我聽到他們在玩,有時候我不會,我不知道爲什麼。

回答

0

好的。在這裏,如果有人像我一樣被困住了。問題是因爲我在Textblock上設置了Tap事件,而不是Button

我是如何從Button.Content獲得內容的?我使用tag屬性,我將它綁定到SongName屬性。