방법: Windows Form에서 소리 재생 반복
다음 코드 예제에서는 소리를 반복해서 재생합니다. stopPlayingButton_Click 이벤트 처리기의 코드가 실행되면 현재 재생 중인 소리가 중지됩니다. 재생 중인 소리가 없으면 아무런 작업도 수행하지 않습니다.
예제
Imports System
Imports System.Media
Imports System.Windows.Forms
Public Class Form1
Inherits System.Windows.Forms.Form
Private Player As New SoundPlayer
Sub New()
Me.InitializeComponent()
End Sub
Private Sub playLoopingButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles playLoopingButton.Click
Try
' Note: You may need to change the location specified based on
' the sounds loaded on your computer.
Me.Player.SoundLocation = "C:\Windows\Media\chimes.wav"
Me.Player.PlayLooping()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error playing sound")
End Try
End Sub
Private Sub stopPlayingButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles stopPlayingButton.Click
Me.Player.Stop()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
Friend WithEvents playLoopingButton As System.Windows.Forms.Button
Friend WithEvents stopPlayingButton As System.Windows.Forms.Button
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.playLoopingButton = New System.Windows.Forms.Button
Me.stopPlayingButton = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'playLoopingButton
'
Me.playLoopingButton.Location = New System.Drawing.Point(12, 12)
Me.playLoopingButton.Name = "playLoopingButton"
Me.playLoopingButton.Size = New System.Drawing.Size(89, 23)
Me.playLoopingButton.TabIndex = 0
Me.playLoopingButton.Text = "Play Looping"
Me.playLoopingButton.UseVisualStyleBackColor = True
'
'stopPlayingButton
'
Me.stopPlayingButton.Location = New System.Drawing.Point(107, 12)
Me.stopPlayingButton.Name = "stopPlayingButton"
Me.stopPlayingButton.Size = New System.Drawing.Size(75, 23)
Me.stopPlayingButton.TabIndex = 1
Me.stopPlayingButton.Text = "Stop"
Me.stopPlayingButton.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(197, 52)
Me.Controls.Add(Me.stopPlayingButton)
Me.Controls.Add(Me.playLoopingButton)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Media;
using System.Windows.Forms;
namespace SoundPlayerPlayLoopingExample
{
public class Form1 : Form
{
private SoundPlayer Player = new SoundPlayer();
public Form1()
{
InitializeComponent();
}
private void playLoopingButton_Click(object sender, EventArgs e)
{
try
{
// Note: You may need to change the location specified based on
// the sounds loaded on your computer.
this.Player.SoundLocation = @"C:\Windows\Media\chimes.wav";
this.Player.PlayLooping();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error playing sound");
}
}
private void stopPlayingButton_Click(object sender, EventArgs e)
{
this.Player.Stop();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.playLoopingButton = new System.Windows.Forms.Button();
this.stopPlayingButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// playLoopingButton
//
this.playLoopingButton.Location = new System.Drawing.Point(12, 12);
this.playLoopingButton.Name = "playLoopingButton";
this.playLoopingButton.Size = new System.Drawing.Size(87, 23);
this.playLoopingButton.TabIndex = 0;
this.playLoopingButton.Text = "Play Looping";
this.playLoopingButton.UseVisualStyleBackColor = true;
this.playLoopingButton.Click += new System.EventHandler(this.playLoopingButton_Click);
//
// stopPlayingButton
//
this.stopPlayingButton.Location = new System.Drawing.Point(105, 12);
this.stopPlayingButton.Name = "stopPlayingButton";
this.stopPlayingButton.Size = new System.Drawing.Size(75, 23);
this.stopPlayingButton.TabIndex = 1;
this.stopPlayingButton.Text = "Stop";
this.stopPlayingButton.UseVisualStyleBackColor = true;
this.stopPlayingButton.Click += new System.EventHandler(this.stopPlayingButton_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(195, 51);
this.Controls.Add(this.stopPlayingButton);
this.Controls.Add(this.playLoopingButton);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button playLoopingButton;
private System.Windows.Forms.Button stopPlayingButton;
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
코드 컴파일
이 예제에는 다음 사항이 필요합니다.
System 및 System.Windows.Forms 어셈블리에 대한 참조
파일 이름 "c:\Windows\Media\chimes.wav"를 올바른 파일 이름으로 변경
Visual Basic 또는 Visual C#의 명령줄에서 이 예제를 빌드하는 방법에 대한 자세한 내용은 명령줄에서 빌드(Visual Basic) 또는 csc.exe를 사용한 명령줄 빌드를 참조하십시오. Visual Studio에서 코드를 새 프로젝트에 붙여넣어 이 예제를 빌드할 수도 있습니다. 자세한 내용은 다음을 참조하십시오. 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행 및 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행 및 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행 및 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행 및 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행.
강력한 프로그래밍
파일 작업은 적절한 예외 처리 블록 내에 있어야 합니다.
다음 조건에서 예외가 발생합니다.
경로 이름의 형식이 잘못된 경우. 예를 들어, 잘못된 문자를 포함하거나 공백만 포함하는 경우(ArgumentException 클래스)
경로가 읽기 전용인 경우(IOException 클래스)
경로 이름이 Nothing인 경우(ArgumentNullException 클래스)
경로 이름이 너무 긴 경우(PathTooLongException 클래스)
경로가 잘못된 경우(DirectoryNotFoundException 클래스)
경로가 콜론 ":"인 경우(NotSupportedException 클래스)
보안
파일 이름을 바탕으로 파일 내용을 판단하면 안 됩니다. 예를 들어, Form1.vb 파일이 Visual Basic 소스 파일이 아닐 수 있습니다. 응용 프로그램에서 데이터를 사용하기 전에 모든 입력을 확인해야 합니다.