Search code examples
windows-phone-8

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


I have tried this code, but it doesn't work.

 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)
        {

        }
    }

how to play an audio file randomly ?


Solution

  • Try this

    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);
        }
    }