Windows Phone声音播放

时间:2012-04-06 15:56:27

标签: c# .net silverlight windows-phone-7 audio-streaming

我有很多.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有时我会听到他们玩,有时候我不会,我不知道为什么会这样。

1 个答案:

答案 0 :(得分:0)

行。在这里,如果有人像我一样被困。问题是因为我在Tap上设置了Textblock事件,而不是Button

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

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