Windows Phone 8:如何使用MediaElement类播放音频文件?

时间:2013-01-26 17:15:40

标签: windows-phone-8 mediaelement

我正在使用MediaElement类并尝试播放我在解决方案资源管理器中添加的音频文件(.mp3)(参见下图)。

我在构造函数

中使用以下代码
// Constructor
public MainPage()
{
    InitializeComponent();

    // Set the data context of the listbox control to the sample data
    DataContext = App.ViewModel;

    MediaElement el = new MediaElement();
    el.Source = new Uri("horse.mp3", UriKind.RelativeOrAbsolute);
    el.Play();
}

我还在下面添加了一个截图,只是为了了解horse.mp3文件所在的位置。

请帮我解决这个问题。

enter image description here

3 个答案:

答案 0 :(得分:2)

MP3文件的构建操作是什么?对于您使用的URI格式,它应该是Build Action = Content。

此外,您实际上并没有将MediaElement添加到您的页面。 MediaElement是一个可视控件,需要成为可视tre的一部分才能运行。如果你想在WP7 / WP8上做短音效,你应该使用XNA的SoundEffect。您必须非常专门地预先格式化您的音频轨道,但您将获得与用户当前正在播放的音频重叠的好处,而无需将其添加到可视树中。

答案 1 :(得分:0)

xaml中的

<Button x:Name="PlayFile"
            Click="PlayFile_Click_1"
            Content="Play mp3" />

并在代码中:

MediaElement MyMedia = new MediaElement();
// Constructor
public MainPage()
{
    InitializeComponent();

    this.LayoutRoot.Children.Add(MyMedia);

    MyMedia.CurrentStateChanged += MyMedia_CurrentStateChanged;
    MyMedia.MediaEnded += MyMedia_MediaEnded;
}

void MyMedia_MediaEnded(object sender, RoutedEventArgs e)
{
    System.Diagnostics.Debug.WriteLine("Ended event " + MyMedia.CurrentState.ToString());
    // Set the source to null, force a Close event in current state
    MyMedia.Source = null;
}

void MyMedia_CurrentStateChanged(object sender, RoutedEventArgs e)
{

    switch (MyMedia.CurrentState)
    {
        case System.Windows.Media.MediaElementState.AcquiringLicense:
            break;
        case System.Windows.Media.MediaElementState.Buffering:
            break;
        case System.Windows.Media.MediaElementState.Closed:
            break;
        case System.Windows.Media.MediaElementState.Individualizing:
            break;
        case System.Windows.Media.MediaElementState.Opening:
            break;
        case System.Windows.Media.MediaElementState.Paused:
            break;
        case System.Windows.Media.MediaElementState.Playing:
            break;
        case System.Windows.Media.MediaElementState.Stopped:
            break;
        default:
            break;
    }

    System.Diagnostics.Debug.WriteLine("CurrentState event " + MyMedia.CurrentState.ToString());
}

private void PlayFile_Click_1(object sender, RoutedEventArgs e)
{
    // Play Awesome music file, stored as content in the Assets folder in your app
    MyMedia.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
    MyMedia.Play();
}

答案 2 :(得分:0)

您必须添加

el.AutoPlay=true

希望得到这个帮助。

相关问题