在 WP8 中单击按钮时如何随机播放音频?

How can I play an audio random when a button is clicked in WP8?

我试过这段代码,但它不起作用。

 public void Play()
    {
        int randomIndex = -1;
        var sound1 = "/Assets/Audio/baby-crying-08.mp3";
        var sound2 = "/Assets/Audio/sound1.wav";
        string [] rawRef = {sound1,sound2};
        MediaElement mp = new MediaElement();
        try
        {
            randomIndex = random.Next(rawRef.Length);
           mp.Source = new Uri(rawRef[randomIndex], UriKind.RelativeOrAbsolute);
           mp.Play();
        }
        catch (Exception e)
        {

        }
    }

如何随机播放音频文件?

我遇到了这个问题。媒体打开后,您需要使用 Play() 方法。此外,您需要将 MediaElement 控件添加到您的 xaml。请记住检查您的文件路径。查找此代码:

MainPage.xaml.cs:

private Random _random = new Random();

public void Play()
{
    int randomIndex = -1;
    var sound1 = "/Assets/cos.wav";
    var sound2 = "/Assets/xx.mp3";
    string[] rawRef = { sound1, sound2 };
    try
    {
        randomIndex = _random.Next(rawRef.Length);
        MediaElement.Source = new Uri(rawRef[randomIndex], UriKind.RelativeOrAbsolute);
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}

private void OnMediaOpened(object sender, RoutedEventArgs e)
{
    MediaElement.Play();
}

private void OnMediaFailed(object sender, ExceptionRoutedEventArgs e)
{
    Debug.WriteLine("Exception: {0}, Sound: {1}", e.ErrorException.Message, MediaElement.Source.ToString());
}

MainPage.xaml:

<MediaElement x:Name="MediaElement" AutoPlay="False" 
              MediaOpened="OnMediaOpened" 
              MediaFailed="OnMediaFailed" />

试试这个

MainPage.xaml:

 <MediaElement x:Name="audio0" Source="/Audio/xh.mp3" AutoPlay="False" />
 <MediaElement x:Name="audio1" Source="/Audio/y.mp3" AutoPlay="False" /> 

MainPage.xaml.cs:

private Random _random = new Random();
private  int randomIndex = -1;
public void Playsound()
{  
    MediaElement [] rawRef = { audio0, audio1 };
    try
    {
        randomIndex = _random.Next(rawRef.Length);                
        if(randomIndex==0)
        {
            audio0.Play();
        }
        else if (randomIndex == 1)
        {
            audio1.Play();
        }
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
        MessageBox.Show("Message:"+e.Message);
    }
}