How to play wav files with SharpDX XAudio2

  • Thread starter Thread starter hirohiro3750
  • Start date Start date
H

hirohiro3750

Guest
Hi

I have a problem with playing wav files with SharpDX XAudio2 on Visual Studio 2019

The following chord worked well on Visual Studio 2016. But it does not on Visual Studio 2019




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


using SharpDX.IO;
using SharpDX.Multimedia;
using SharpDX.XAudio2;


namespace WpfApp9
{

public partial class MainWindow : Window
{

private WavePlayer _wavePlayer = new WavePlayer();
public MainWindow()
{
InitializeComponent();

_wavePlayer.AddWave("piano-c", "piano-c.wav");
}

public class WavePlayer : IDisposable
{
public bool IsSoundOn { get; set; }



private readonly XAudio2 xAudio;
readonly Dictionary<string, MyWave> sounds;

public WavePlayer()
{
xAudio = new XAudio2();
xAudio.StartEngine();
var masteringVoice = new MasteringVoice(xAudio);
masteringVoice.SetVolume(1);
sounds = new Dictionary<string, MyWave>();
}

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


sounds.Add(key, wave);
}

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

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

public void Dispose()
{
xAudio.Dispose();
}
}


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


private void button_Click(object sender, RoutedEventArgs e)
{

_wavePlayer.PlayWave("piano-c");


}
}
}


Incidentally, this is the error I got when I played a wav file. 1618669.png

Continue reading...
 
Back
Top