C# Media Player Mp3

C# 2021. 11. 21. 13:27 |
반응형

C#에서 MP3파일을 플레이 해 보자.

 

Solution Explorer - References 우클릭 - Add Reference... 클릭

 

PresentationCore 선택.

 

WindowsBase 선택.

 

폼과 버튼을 적당히 배치한다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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.Windows.Media;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        enum STATE {PLAYING, STOPPED, PAUSED }
 
        STATE state;
        private string time;
 
        MediaPlayer MP;
 
        public Form1()
        {
            InitializeComponent();
 
            state = STATE.STOPPED;
            MP = new MediaPlayer();
 
            Timer T = new Timer();
            T.Interval = 1000;
            T.Tick += new EventHandler(Form1_Timer);
            T.Start();            
        }
 
        private void Form1_Timer(object sender, System.EventArgs e)
        {
            if (state == STATE.PLAYING && MP.NaturalDuration.HasTimeSpan)
            {
                time = MP.Position.ToString(@"hh\:mm\:ss"+ " / "
                    + MP.NaturalDuration.TimeSpan.ToString(@"hh\:mm\:ss");
 
                Graphics G = CreateGraphics();
                //G.DrawString(time, Font, System.Drawing.Brushes.Black, 20, 90); // 글자가 겹친다.
                TextRenderer.DrawText(G, time, Font, new Point(2090), ForeColor, BackColor);
                G.Dispose();
            }            
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    MP.Open(new Uri(dlg.FileName));
                    MP.Play();
                    state = STATE.PLAYING;
                }
            } catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }            
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            MP.Stop();
            MP.Close();
            state = STATE.STOPPED;
        }
    }
}
 

 

소스를 입력한다.

 

프로그램을 실행하고 파일을 선택하면 플레이 된다.

 

반응형
Posted by J-sean
: