问题描述
我创建要求对环状背景音乐不同的音效来播放(按下按钮),一个WP7的应用程序。背景音乐可以通过按按钮1发起和循环罚款。当我按下按钮3(触发声音效果),对一按背景音乐的细微声音效果叠加。然而,当我再次按下按钮3,背景音乐停止。我想不通,为什么这可能发生!?我已经粘贴下面的代码的相关部分。 。希望得到任何帮助。
I am creating a WP7 application that requires various sound effects to be played (on button press) over looped background music. The background music is initiated by pressing Button 1 and loops fine. When I press button3 (triggers a sound effect), the sound effect overlays on the background music fine on first press. However, when I press button3 again, the background music stops. I cannot figure out why this might be happening!? I have pasted the relevant portions of code below. Would appreciate any help.
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");
}
}
}
}
推荐答案
这应该工作,如果你总是用实例合作,以便更改您的代码这一点,它应该清理的问题:
This should work if you are always working with Instances so change your code to this and it should clear up the problem:
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");
}
}
上面的例子假设你的声音文件设置与生成操作=内容并在顶级目录。
The above example assumes your sound files are set with Build Action = Content and are in the top level directory.
这篇关于同时演奏两个音色C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!