我正在学习如何使用xAudio2。在Visual Studio 2012 Express for Windows 8中制作了一个简单的Windows 8应用程序。 简单的xAudio2播放器类:
public class SoundEffect
{
readonly XAudio2 _xaudio;
readonly WaveFormat _waveFormat;
readonly AudioBuffer _buffer;
readonly SoundStream _soundstream;
SourceVoice sourceVoice;
public SoundEffect(string soundFxPath)
{
_xaudio = new XAudio2();
var masteringsound = new MasteringVoice(_xaudio);
var nativefilestream = new NativeFileStream(
soundFxPath,
NativeFileMode.Open,
NativeFileAccess.Read,
NativeFileShare.Read);
_soundstream = new SoundStream(nativefilestream);
_waveFormat = _soundstream.Format;
_buffer = new AudioBuffer
{
Stream = _soundstream.ToDataStream(),
AudioBytes = (int)_soundstream.Length,
Flags = BufferFlags.EndOfStream
};
//sourceVoice = null;
}
public void Play()
{
sourceVoice = new SourceVoice(_xaudio, _waveFormat, true);
if (sourceVoice != null)
{
sourceVoice.FlushSourceBuffers();
sourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
sourceVoice.Start();
}
}
public void Stop()
{
sourceVoice.Stop();
}
}
和Xaml:
<Border Background="Gray" MinHeight="150" MinWidth="150" Margin="10,10,0,0" x:Name="A" PointerPressed="btnAPointerPressed" PointerReleased="btnAPointerReleased" />
和
private SoundEffect shotEffect = new SoundEffect(@"sounds\mywav.wav");
private void btnAPointerPressed(object sender, PointerRoutedEventArgs e)
{
bool _hasCapture = ((Border)sender).CapturePointer(e.Pointer);
shotEffect.Play();
}
private void btnAPointerReleased(object sender, PointerRoutedEventArgs e)
{
((Border)sender).ReleasePointerCapture(e.Pointer);
shotEffect.Stop();
}
在Windows 8 Simulator中测试。 如果我按一个手指,那么一切都很好。 当我点击按钮时 - 当我放开手指时声音播放 - 声音停止。
如果我用两根手指点击并放开两根手指,声音会继续播放。结果就是别名。
调用两个事件:btnAPointerPressed和两个事件:btnAPointerReleased但声音继续播放。好像音频流冻结并继续播放。好像音频流冻结并继续播放。 我想了解haudio2的问题?或者我做得不好?
答案 0 :(得分:1)
当您再次致电Play()
时,之前的SourceVoice
会被SoundEffect
中的新{{1}}取代,但您永远不会停止旧的{{1}}。您应该在每次触摸时创建一个新的SourceVoice,但要将它们全部与指针ID相关联,这样我们就可以在释放相关指针时停止它们。