Portfolio

Friday, November 13, 2015

How to Play Sounds in Your Application?

Sound App in C#


Introduction

Doing this application was a blast.  It allowed me to mess around with .wav files.  You could put just about any sound, such as a movie quote, animal sounds, or machines beeping.  It is entirely up to you.  In this application I added a duck quack and sounds from your actual computer.  

What you need?

You will need Visual Studio.  
Start in Windows Forms Application
About 7 buttons
7 labels 
Creativity

Source code:

On each button click event attach the appropriate sound by double clicking the button to go to the source code.  You also can view the source code screen by pressing F7.  Copy the code and explore with .wav sounds.  Don't forget the Using.System.Media namespace at the top.  I've highlighted the namespace for you.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;

namespace PlayingSounds
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog() == DialogResult.OK)
            {
                SoundPlayer s = new SoundPlayer(ofd.FileName);
                s.Play();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
           
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                SoundPlayer s = new SoundPlayer(ofd.FileName);
                s.PlayLooping();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SystemSounds.Asterisk.Play();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            SystemSounds.Beep.Play();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            SystemSounds.Exclamation.Play();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            SystemSounds.Hand.Play();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                SoundPlayer s = new SoundPlayer(ofd.FileName);
                s.Play();
            }
        }
    }
}


No comments:

Post a Comment