C#中Play Sound

using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Diagnostics;
using  System.Drawing;
using  System.Media;
using  System.Windows.Forms;

namespace  SoundApiExample
{
    
public class SoundTestForm : System.Windows.Forms.Form
    
{
        
private System.Windows.Forms.Label label1;
        
private System.Windows.Forms.TextBox filepathTextbox;        
        
private System.Windows.Forms.Button playOnceSyncButton;
        
private System.Windows.Forms.Button playOnceAsyncButton;
        
private System.Windows.Forms.Button playLoopAsyncButton;
        
private System.Windows.Forms.Button selectFileButton;
        
        
private System.Windows.Forms.Button stopButton;
        
private System.Windows.Forms.StatusBar statusBar;
        
private System.Windows.Forms.Button loadSyncButton;
        
private System.Windows.Forms.Button loadAsyncButton;        
        
private SoundPlayer player;

        
public SoundTestForm()
        
{
            
// Initialize Forms Designer generated code.
            InitializeComponent();
            
            
// Disable playback controls until a valid .wav file 
            
// is selected.
            EnablePlaybackControls(false);

            
// Set up the status bar and other controls.
            InitializeControls();

            
// Set up the SoundPlayer object.
            InitializeSound();
        }


        
// Sets up the status bar and other controls.
        private void InitializeControls()
        
{
            
// Set up the status bar.
            StatusBarPanel panel = new StatusBarPanel();
            panel.BorderStyle 
= StatusBarPanelBorderStyle.Sunken;
            panel.Text 
= "Ready.";
            panel.AutoSize 
= StatusBarPanelAutoSize.Spring;
            
this.statusBar.ShowPanels = true;
            
this.statusBar.Panels.Add(panel);
        }


        
// Sets up the SoundPlayer object.
        private void InitializeSound()
        
{
            
// Create an instance of the SoundPlayer class.
            player = new SoundPlayer();

            
// Listen for the LoadCompleted event.
            player.LoadCompleted += new AsyncCompletedEventHandler(player_LoadCompleted);

            
// Listen for the SoundLocationChanged event.
            player.SoundLocationChanged += new EventHandler(player_LocationChanged);
        }


        
private void selectFileButton_Click(object sender, 
            System.EventArgs e)
        
{
            
// Create a new OpenFileDialog.
            OpenFileDialog dlg = new OpenFileDialog();

            
// Make sure the dialog checks for existence of the 
            
// selected file.
            dlg.CheckFileExists = true;

            
// Allow selection of .wav files only.
            dlg.Filter = "WAV files (*.wav)|*.wav";
            dlg.DefaultExt 
= ".wav";

            
// Activate the file selection dialog.
            if (dlg.ShowDialog() == DialogResult.OK)
            
{
                
// Get the selected file's path from the dialog.
                this.filepathTextbox.Text = dlg.FileName;

                
// Assign the selected file's path to 
                
// the SoundPlayer object.  
                player.SoundLocation = filepathTextbox.Text;
            }

        }


        
// Convenience method for setting message text in 
        
// the status bar.
        private void ReportStatus(string statusMessage)
        
{
            
// If the caller passed in a message...
            if ((statusMessage != null&& (statusMessage != String.Empty))
            
{
                
// ...post the caller's message to the status bar.
                this.statusBar.Panels[0].Text = statusMessage;
            }

        }

        
        
// Enables and disables play controls.
        private void EnablePlaybackControls(bool enabled)
        
{   
            
this.playOnceSyncButton.Enabled = enabled;
            
this.playOnceAsyncButton.Enabled = enabled;
            
this.playLoopAsyncButton.Enabled = enabled;
            
this.stopButton.Enabled = enabled;
        }

    
        
private void filepathTextbox_TextChanged(object sender, 
            EventArgs e)
        
{
            
// Disable playback controls until the new .wav is loaded.
            EnablePlaybackControls(false);
        }


        
private void loadSyncButton_Click(object sender, 
            System.EventArgs e)
        
{   
            
// Disable playback controls until the .wav is 
            
// successfully loaded. The LoadCompleted event 
            
// handler will enable them.
            EnablePlaybackControls(false);

            
try
            
{
                
// Assign the selected file's path to 
                
// the SoundPlayer object.  
                player.SoundLocation = filepathTextbox.Text;

                
// Load the .wav file.
                player.Load();
            }

            
catch (Exception ex)
            
{
                ReportStatus(ex.Message);
            }

        }


        
private void loadAsyncButton_Click(System.Object sender, 
            System.EventArgs e)
        
{
            
// Disable playback controls until the .wav is 
            
// successfully loaded. The LoadCompleted event 
            
// handler will enable them.
            EnablePlaybackControls(false);

            
try
            
{
                
// Assign the selected file's path to 
                
// the SoundPlayer object.  
                player.SoundLocation = this.filepathTextbox.Text;

                
// Load the .wav file.
                player.LoadAsync();
            }

            
catch (Exception ex)
            
{
                ReportStatus(ex.Message);
            }

        }


        
// Synchronously plays the selected .wav file once.
        
// If the file is large, UI response will be visibly 
        
// affected.
        private void playOnceSyncButton_Click(object sender, 
            System.EventArgs e)
        
{    
            ReportStatus(
"Playing .wav file synchronously.");
            player.PlaySync();
            ReportStatus(
"Finished playing .wav file synchronously.");
        }


        
// Asynchronously plays the selected .wav file once.
        private void playOnceAsyncButton_Click(object sender, 
            System.EventArgs e)
        
{
            ReportStatus(
"Playing .wav file asynchronously.");
            player.Play();
        }


        
// Asynchronously plays the selected .wav file until the user
        
// clicks the Stop button.
        private void playLoopAsyncButton_Click(object sender, 
            System.EventArgs e)
        
{
            ReportStatus(
"Looping .wav file asynchronously.");
            player.PlayLooping();
        }


        
// Stops the currently playing .wav file, if any.
        private void stopButton_Click(System.Object sender,
            System.EventArgs e)
        
{    
            player.Stop();
            ReportStatus(
"Stopped by user.");
        }


        
// Handler for the LoadCompleted event.
        private void player_LoadCompleted(object sender, 
            AsyncCompletedEventArgs e)
        
{   
            
string message = String.Format("LoadCompleted: {0}"
                
this.filepathTextbox.Text);
            ReportStatus(message);
            EnablePlaybackControls(
true);
        }


        
// Handler for the SoundLocationChanged event.
        private void player_LocationChanged(object sender, EventArgs e)
        
{   
            
string message = String.Format("SoundLocationChanged: {0}"
                player.SoundLocation);
            ReportStatus(message);
        }

 

or

 

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Media;

namespace  LinkPair
{
    
public class GameMusic
    
{
        
/// <summary>
        
/// WAV文件路径
        
/// </summary>

        string strMusicPath;

        
/// <summary>
        
/// 是否循环播放
        
/// </summary>

        bool isLoop;

        
/// <summary>
        
/// 获取或设置WAV文件路径
        
/// </summary>

        public string MusicPath
        
{
            
get
            
{
                
return this.strMusicPath;
            }

            
set
            
{
                
this.strMusicPath = value;
            }

        }


        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="musicPath">WAV文件路径</param>

        public GameMusic(string musicPath, bool isLoop)
        
{
            
this.strMusicPath = musicPath;
            
this.isLoop = isLoop;
        }


        
/// <summary>
        
/// 播放WAV文件
        
/// </summary>
        
/// <returns></returns>

        public bool PlayWav()
        
{
            SoundPlayer sndPing 
= new SoundPlayer(strMusicPath);

            
if (this.isLoop)
            
{
                sndPing.PlayLooping();
            }

            
else
            
{
                sndPing.Play();
            }


            
return true;
        }

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值