[英]Playing two sounds simultaneously c#
我正在創建一個WP7應用程序,需要在循環背景音樂上播放(按下按鈕)各種聲音效果。 通過按下按鈕1啟動背景音樂並循環播放。 當我按下按鈕3(觸發聲音效果)時,首次按下時背景音樂上的聲音效果會很好。 但是,當我再次按下按鈕3時,背景音樂停止。 我無法弄清楚為什么會發生這種情況!? 我已粘貼下面的相關代碼部分。 非常感謝任何幫助。
public partial class MainPage : PhoneApplicationPage
{
SoundEffect soundEffect;
Stream soundfile;
// Constructor
public MainPage()
{
InitializeComponent();
}
static protected void LoopClip(SoundEffect soundEffect)
{
{
SoundEffectInstance instance = soundEffect.CreateInstance();
instance.IsLooped = true;
FrameworkDispatcher.Update();
instance.Play();
}
}
public void PlaySound(string soundFile)
{
using (var stream = TitleContainer.OpenStream(soundFile))
{
var effect = SoundEffect.FromStream(stream);
effect.Play();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
soundfile = TitleContainer.OpenStream("BackgroundMusic.wav");
soundEffect = SoundEffect.FromStream(soundfile);
LoopClip(soundEffect);
}
private void button3_Click(object sender, RoutedEventArgs e)
{
PlaySound("sound3.wav");
}
}
}
如果您始終使用Instances,這應該有效,所以將代碼更改為此,它應該清除問題:
public partial class MainPage : PhoneApplicationPage
{
SoundEffectInstance loopedSound = null;
// Constructor
public MainPage()
{
InitializeComponent();
}
static protected void LoopClip(SoundEffect soundEffect)
{
loopedSound = soundEffect.CreateInstance();
loopedSound.IsLooped = true;
loopedSound.Play();
}
public void PlaySound(string soundFile)
{
SoundEffect sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri(soundFile, UriKind.Relative)).Stream);
SoundEffectInstance instance = sound.CreateInstance();
instance.Play();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
SoundEffect sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri(@"BackgroundMusic.wav", UriKind.Relative)).Stream);
LoopClip(sound);
}
private void button3_Click(object sender, RoutedEventArgs e)
{
PlaySound("sound3.wav");
}
}
上面的示例假設您的聲音文件是使用Build Action = Content設置的,並且位於頂級目錄中。
您需要從單獨的線程播放每個聲音。
這里似乎發生的是,不同的Play
方法調用彼此干擾,因為它們在同一個線程中。
嘗試將背景音樂放在一個單獨的線程中,看看是否能解決您在問題中提到的問題。 如果是這樣,也將其他人分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.