如何在 WinRT 中使用 SharpDX 同时播放多个声音? [英] How can I play multiple sounds at the same time using SharpDX in WinRT?

查看:37
本文介绍了如何在 WinRT 中使用 SharpDX 同时播放多个声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一种乐器类型的应用程序.我遇到的问题是只有在旧声音完成后才会播放新声音.我希望能够同时播放它们.

I am trying to make a musical instrument type of application. The problem I am having is that a new sound will only play if the old one is finished. I would like to be able to play them simultaneously.

这是我的代码的样子:

首先,MyWave 类只包含一个音频缓冲区和一些其他信息:

First, the MyWave class which simply holds an audio buffer and some other info:

class MyWave
{
    public AudioBuffer Buffer { get; set; }
    public uint[] DecodedPacketsInfo { get; set; }
    public WaveFormat WaveFormat { get; set; }
}

在 SoundPlayer 类中:

In the SoundPlayer class:

    private XAudio2 xaudio;
    private MasteringVoice mvoice;
    Dictionary<string, MyWave> sounds;

    // Constructor
    public SoundPlayer()
    {
        xaudio = new XAudio2();
        xaudio.StartEngine();
        mvoice = new MasteringVoice(xaudio);
        sounds = new Dictionary<string, MyWave>();
    }

    // Reads a sound and puts it in the dictionary
    public void AddWave(string key, string filepath)
    {
        MyWave wave = new MyWave();

        var nativeFileStream = new NativeFileStream(filepath, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);
        var soundStream = new SoundStream(nativeFileStream);
        var buffer = new AudioBuffer() { Stream = soundStream, AudioBytes = (int)soundStream.Length, Flags = BufferFlags.EndOfStream };

        wave.Buffer = buffer;
        wave.DecodedPacketsInfo = soundStream.DecodedPacketsInfo;
        wave.WaveFormat = soundStream.Format;

        this.sounds.Add(key, wave);
    }

    // Plays the sound
    public void Play(string key)
    {
        if (!this.sounds.ContainsKey(key)) return;
        MyWave w = this.sounds[key];

        var sourceVoice = new SourceVoice(this.xaudio, w.WaveFormat);
        sourceVoice.SubmitSourceBuffer(w.Buffer, w.DecodedPacketsInfo);
        sourceVoice.Start();
    }
}

谷歌不是很有帮助,我找不到任何有用的东西.那么如何同时播放多个声音?

Google wasn't very helpful, I couldn't find anything useful. So how can I play multiple sounds simultaneously?

推荐答案

您必须创建(最好是汇集)多个 SourceVoice 实例并同时播放它们.

You'll have to create (and preferably pool) multiple SourceVoice instances and play them back simultaneously.

事实上,您当前的代码应该可以工作,不是吗?您可能希望在SourceVoice 中添加StreamEnd 事件侦听器以在播放完成后自行处置,并记得在调用SourceVoice 的构造函数时启用回调.

In fact, your current code should work, no? You may want to add a StreamEnd event listener to the SourceVoice to dispose of itself after playback is complete, and remember to enable callbacks when calling the constructor of the SourceVoice.

这篇关于如何在 WinRT 中使用 SharpDX 同时播放多个声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆