//Here's the code, pretty straightforward
//Download this Project in Visual Studio 2008 Format
//download and install the directx SDK
using System;
using System.Windows.Forms;
using Microsoft.DirectX.AudioVideoPlayback;
using Microsoft.DirectX.DirectSound;
namespace MusicAndSound {
public partial class Form1 : Form {
private Audio musicAudio;
public Form1()
{
InitializeComponent();
}
private void btnBrowseMusic_Click(object sender, EventArgs e)
{
GrabFileNameIntoTextBox(txtMusicFileName,"Music (*.mp3) |*.mp3|All Files (*.*) |*.*");
}
private void GrabFileNameIntoTextBox(TextBox box, string filter)
{
FileDialog dialog = new OpenFileDialog();
dialog.Filter = filter;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
box.Text = dialog.FileName;
}
}
private void btnBrowseSound_Click(object sender, EventArgs e)
{
GrabFileNameIntoTextBox(txtSoundFileName,"Sound (*.wav) |*.wav|All Files (*.*) |*.*");
}
private void btnPlayMusic_Click(object sender, EventArgs e)
{
if (MusicIsStopped())
{
PlayMusic(txtMusicFileName.Text);
}
else {
StopMusic();
}
}
private void StopMusic()
{
musicAudio.Stop();
musicAudio.Dispose();
musicAudio = null;
btnPlayMusic.Text = "Play Music";
}
private void PlayMusic(string songFile)
{
musicAudio = new Audio(songFile, true);
//loop it musicAudio.Ending += ReplayMusic;
btnPlayMusic.Text = "Stop Music";
}
private bool MusicIsStopped()
{
return btnPlayMusic.Text == "Play Music";
}
private void ReplayMusic(object sender, EventArgs e)
{
//makes it keep looping. musicAudio.Stop();
musicAudio.Play();
}
private void btnPlaySound_Click(object sender, EventArgs e)
{
try {
PlaySound(txtSoundFileName.Text);
}
catch (ArgumentException)
{
MessageBox.Show("Invalid Sound File format. Try a wav file for example");
}
}
private void PlaySound(string soundFile)
{
var soundDevice = new Device();
soundDevice.SetCooperativeLevel(this, CooperativeLevel.Normal);
var buffer = new SecondaryBuffer(soundFile, soundDevice);
buffer.Play(0, BufferPlayFlags.Default);
}
}
}