我已尝试过此代码,但它不起作用。
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)
{
}
}
如何随机播放音频文件?
答案 0 :(得分:5)
我有这个问题。打开媒体后,您需要使用Play()
方法。此外,您需要为您的xaml添加MediaElement
控件。请记住检查文件路径。寻找这段代码:
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" />
答案 1 :(得分:0)
试试这个
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);
}
}