Windows Phone 声音播放

本文关键字:播放 声音 Phone Windows | 更新日期: 2023-09-27 18:30:27

我有很多.wav文件要播放,因此我创建了AudioItem类:

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有时我听到他们演奏,有时我没有,我不知道为什么会这样。

Windows Phone 声音播放

好的。就是这样,如果有人像我一样被困住。问题是因为我将Tap事件设置在Textblock上,而不是Button

我是如何从Button.Content获得内容的?

我使用tag属性并将其绑定到SongName属性。