1. 음악 플레이어의 구현 원리
Javase의 멀티미디어 기능은 매우 약하므로 JMF라는 멀티미디어를 전문으로하는 플러그인이 있습니다. JMF가 제공하는 모델은 대략 7 가지 범주로 나눌 수 있습니다.
* 데이터 소스
* 캡처 장치 (비디오 및 오디오 인터셉터 포함)
* 플레이어
* 프로세서
* DataSink
* 데이터 형식 (형식)
* 관리자
Music Player MyMusicPlayer (이것은 내가 만든 클래스 이름입니다) JMF의 플레이어 클래스에 전화하여 재생과 같은 다양한 기능을 구현했습니다.
우리가해야 할 첫 번째 일은 JMF를 설치하는 것입니다. JMF의 설치는 많은 초보자에게 매우 번거 롭다고 생각합니다. JMF는 32 비트 JDK 버전 만 지원하지만 Eclipse와 같은 IDE 환경은 JDK에 해당해야합니다. 즉 IDE 환경은 32 비트 JDK 버전을 지원해야합니다. JMF를 설치 한 후에는 MP3의 재생이 성공하지 못하며 JMF의 MP3Plugin을 설치해야합니다.
2. 인터페이스 효과 다이어그램
3. 기능 구조 다이어그램
4. 기능 구현을위한 다양한 코드
Public Class MyMusicPlayer는 ActionListener, ControlLerListener, Runnable {jframe J = New Jframe ( "Music Player")를 구현합니다. jlabel tableplaer = new Jlabel ( "재생 목록"); JBUTTON BADD = NEW JBUTTON ( "노래 추가"); JBUTTON BDELECT = NEW JBUTTON ( "Delete Song"); JBUTTON BDELECTTABLE = NEW JBUTTON ( "Clear List"); JBUTTON BMOVENEXT = NEW JBUTTON ( "Next Song"); JBUTTON BMOVEPREVIOUS = NEW JBUTTON ( "이전 노래"); JBUTTON BPLAYER = NEW JBUTTON ( "일시 정지"); JBUTTON BSTOP = NEW JBUTTON ( "STOP"); JBUTTON BSET = NEW JBUTTON ( "Show 가사"); JBUTTON BEND = NEW JBUTTON ( "STOP"); 문자열 [] s = { "순차 재생", "단일 루프", "셔터 플레이"}; // 드롭 다운 목록 옵션 배열 jcombobox select = new jcombobox (들); // 드롭 다운 옵션 생성 jpanel p1 = new JPanel (); // 재생 목록 영역 jpanel p = new jpanel (); JPANEL P2 = NEW JPANEL (); // 버튼 영역 JPANEL P3 = 새로운 jpanel (); jlabel l = new Jlabel (); JPANEL P5 = NEW JPANEL (); // 재생 목록 배치 jpanel p6 = new jpanel (); // 재생 노래의 이름을 배치 static jpanel pp = new jpanel (); 정적 Jlabel LB; public static jtextArea jt = 새로운 jtextArea (); 정적 INT 인덱스; // 재생 목록 int count의 첨자; int 플래그; // 재생 목록의 마커는 int countsecond를 무작위로 또는 순차적으로 재생하는 것입니다. // 음악의 총 시간 값을 얻습니다. 정적 int newtime = 0; int ischanging = 0; // 마우스가 커서를 클릭하면 진행 값도 int ispressing = 0을 변경합니다. // 마우스가 커서 파일을 클릭하는지 여부를 방어합니다. musicName = null; static java.util.list <file> musicNames = null; // 제네릭을 사용하여 파일 객체 파일을 만듭니다. currentDirectory = null; 목록 목록; // 파일 목록 Filedialog Open; // 파일 정의 대화 상자 객체 random rand = new random (); 문자열 filename; // Progress Bar JBUTTON TIMEININFORMATION = NEW JBUTTON (); JSLIDER TIMELIDER = NEW JSLIDER (SwingConstants.horizontal, 0, 100, 0); //(swingconstants.horizontal)는 수평 방향으로 진행률 표시 줄로 상수 세트를 지시하는 데 사용됩니다. // (0, 100, 0) 지정된 최소, 최대 및 초기 값으로 수평 슬라이더를 만듭니다. // 플레이어 플레이어 플레이어 = null; musicfilechooser filechooser = new MusicFileChooser (); 정적 jtextpane tp = new JtextPane (); // 가사 영역 표시 정적 jtextArea는 = new JtextArea (); // 이미지 영역 표시 public mymusicplayer () {j.setsize (1200, 700); J.SetLayout (null); j.getContentPane (). setbackground (color.black); J.SetDefaultCloseOperation (jframe.exit_on_close); P. 세트 바운드 (2, 563, 1180, 95); P.SetLayout (New BorderLayout ()); p1. 세트 바운드 (2, 3, 298, 30); p1. 세트 백 그라운드 (새로운 컬러 (255, 255, 255)); P2.SetLayout (New GridLayout (2, 3, 20, 20)); p2.setbackground (color.light_gray); P3.SetLayout (New GridLayout (2,0,200,10)); P3. 세트 백 그라운드 (새로운 색상 (255,255,255)); P5. 세트 바운드 (2, 35, 298, 526); p5. 세트 레이 아웃 (null); P5. 세트 백 그라운드 (새로운 색상 (255,255,255)); p6. 세트 바운드 (301, 3,880, 30); p6. 세트 레이 아웃 (null); p6. 세트 백 그라운드 (새로운 색상 (255,255,255)); L. 세트 바운드 (250, 4, 600, 30); // 표시된 노래를 설정하고 재생 된 노래 p6.add (l); /*이미지 삽입 구현*/imageicon ic = new ImageIcon ( "image // 2.3.jpg"); ic = new ImageIcon (ic.getImage (). getScaledInstance (880, 477, 2)); // 그림을 가져 와서 이미지 크기를 설정합니다 LB = New Jlabel (IC); lb.setopaque (false); pp.setopaque (false); // 투명한 pp.setBounds (241, 80,990, 500)로 설정; are.setBounds (241, 56,990, 520); are.setopaque (false); tp.setbackground (새로운 색상 (255,255,255)); TP. 세트 바운드 (301, 35,880, 49); pp.add (are); pp.add (lb); // 파일 목록 = 새 목록 (10); List.SetBounds (100, 55, 187, 495); // 목록 영역 list.addactionListener (this); J.add (목록); J.add (JT); J.add (TP); Badd.SetBounds (5,20, 90,30); Badd.setbackground (새로운 색상 (255,255,255)); bdelect.setbounds (5, 80, 90, 30); bdelect.setbackground (새로운 색상 (255,255,255)); bdelect.setbounds (5, 140, 90, 30); bdelect.setbackground (새로운 색상 (255,255,255)); TablePlaer.SetBounds (30, 100, 200, 50); tableplaer.setfont (새 글꼴 ( "安安", 1, 20)); p1.add (Tablaer); bmoveprevious.setbackground (새로운 색상 (255,255,255)); Bplayer.setbackground (새로운 색상 (255,255,255)); bmovenext.setbackground (새로운 색상 (255,255,255)); bstop.setbackground (새로운 색상 (255,255,255)); select.setbackground (새 색상 (255,255,255)); bset.setbackground (새로운 색상 (255,255,255)); p2.add (bmoveprevious); p2.add (bplayer); p2.add (bmovenext); p2.add (bstop); p2.add (select); p2.add (bset); P2. 세트 백 그라운드 (새로운 색상 (255,255,255)); p.add (P2, Borderlayout.West); p.add (P3, BorderLayout.Center); P5.ADD (P); p5.add (badd); P5.ADD (BDELECT); p5.ADD (bdeLectTable); badd.addactionListener (this); bdelect.addactionListener (this); bdelecttable.addactionListener (this); bmovenext.addactionListener (this); bplayer.addactionListener (this); bmoveprevious.addactionListener (this); bstop.addactionListener (this); select.addactionListener (this); bset.addactionListener (this); timeInformation.SetEnabled (false); / * * 구현 진행 바 * */timeslider.setmajortickspacing (1); // 메인 스케일 마크의 간격을 설정하려면이 메소드를 호출합니다. 들어오는 숫자는 각 메인 스케일 마커 사이의 값으로 측정 된 거리를 나타냅니다. timeslider.setpaintticks (true); // 메인 스케일을 그리려면 setPaintTicks는 true timeslider.addchangelistener (new ChangeListener () {// 새 Changelistener를 생성하고 슬라이더에 추가합니다. public void statechanged (ChangeEvent arg0) {if (player! = null && is pressing == 1) {newtime = (int) (JSLIDER) arg0.getSource (). getValue (); "현재 시간 :"+newtime%60+"+"총 시간 : "+countecond%60; timeslider.addmouseListener (new MouseAdapter () {public void mousepressed (mouseevent arg0) {ispressing = 1; // 마우스가 커서를 클릭 할 때} public void mouserEleled (mouseevent arg0) {ispressing = 0; //}}}); TimeInformation.settext ( "현재 시간 : 00:00 || 총 시간 : 00:00"); TimeInformation.setbackground (새로운 색상 (255,255,255)); p3.add (timeinformation, borderlayout.north); p3.add (Timeslider, BorderLayout.South); J.add (pp); J.add (p5); J.add (p); J.add (p1); J.add (p6); j.setVisible (true); // j.setResizable (false); } / * * 메인 함수 * * /public static void main (String [] args)은 ioException을 던지고, InterruptedException {// InterruptedException : 스레드가 대기, 수면 또는 점유 상태 일 때, 활동 전이나 활동 중에 스레드가 중단되면, 예외가 발생합니다. MyMusicPlayer Play = New MyMusicPlayer (); 스레드 타이머 런 = 새 스레드 (재생); Timerun.start (); } @override public void ActionPerformed (ActionEvent e) {문자열 cmd = e.getActionCommand (); // 문자열, 문자열 box = (문자열)를 가져 와서 재생할지 여부를 판단합니다. select.getSelectedItem (); // if (e.getSource () == badd) {if (player == null) {if (filechooser.showoPendialog (j) == musicfilechooser.Approve_Option) {this.the. this. this.the.getSelectedFile (); 파일 cd = filechooser.getCurrentDirectory (); // 현재 경로를 가져옵니다. // fileFilter는 jfilechooser가 사용자 파일에 표시된 파일 세트를 필터링하는 데 사용하는 추상 클래스입니다. [] = cd.listfiles (); //cd.listfiles ()는이 추상 PathName으로 표시되는 디렉토리의 파일을 나타내는 추상 PathNames의 배열을 반환하는 것을 의미합니다. this.musicNames = new ArrayList <file> (); for (파일 파일 : 파일) {// 배열의 파일 개체가 파일 변수에 할당 될 때 마다이 변수는 다음과 같은 루프 본문에서 작동됩니다 (int i = 0; i <files.length; i ++) {file = files [i]; ...} filename = file.getName (). // (파일 필터 필터 : fileFilters) {if (! file.isdirectory () && filter.accept (file)) {this.musicNames.add (file); list.add (filename); filename = e.getActionCommand (); }}}}} index = musicNames.IndexOf (musicName); // 노래 count = musicNames.size ()의 첨자를 정의합니다. playfile (); }} else {player.start (); }} if (cmd.equals ( "pause")) {bplayer.settext ( "play"); player.stop (); } if (cmd.equals ( "play")) {bplayer.settext ( "pause"); player.start (); } if (e.getSource () == bstop) {// stop if (player! = null) {player.stop (); TimeInformation.settext ( "현재 시간 : 00 : 00 || 총 시간 : 00 : 00"); timeslider.setValue (0); player.setMediatime (새로운 시간 (0)); // Zero}} if (e.getSource () == bmovenext) {// next song if (player! = null) {if ( "sequal playback".equals (box)) {nextMusic (); } if ( "셔터 재생".equals (box)) {int index = (int) rand.nextInt (this.musicNames.size ())+1; if (this.musicNames! = null &&! this.musicNames.isempty ()) {if (++ index == this.musicNames.size.size ()) {index = (int) rand.nextInt (this.musicNames.size ())+1; } player.stop (); // 이전 노래를 클릭하면 현재 노래가 중지되고 이전 노래가 재생됩니다. {player = manager.createrealizedPlayer (musicNames.get (index) .touri (). tourl ()); player.prefetch (); player.setMediatime (new Time (0.0)); // play player.addControllerListener (this); l.settext ( "재생 :"+this.musicNames.get (index) .toString ()); list.select (색인); player.start (); 플래그 = 1; } catch (noplayerException | can niclerealizeexception | ioexception e1) {e1.printstacktrace (); }}}}}} if (e.getSource () == bmovePrevious) {// previous song if (player! = null) {if ( "sequential play".equals (box)) {previousMusic (); } if ( "셔터 재생".Equals (box)) {int index = (int) rand.nextInt (this.musicNames.size ())+1; if (this.musicNames! = null &&! this.musicNames.isempty ()) {if (index-== (int) rand.nextInt (this.musicNames.size ())+1) {index = this.size.size ()-1; } player.stop (); // 이전 노래를 클릭하면 현재 노래가 중지되고 이전 노래가 재생됩니다. {player = manager.createrealizedPlayer (musicNames.get (index) .touri (). tourl ()); player.prefetch (); player.setMediatime (new Time (0.0)); // 플레이어를 시작하기 시작합니다. l.settext ( "재생 :"+this.musicNames.get (index) .toString ()); list.select (색인); player.start (); 플래그 = 1; } catch (noplayerException | can niclerealizeexception | ioexception e1) {e1.printstacktrace (); }}}}}}} if (e.getSource () == bdelect) {// song index = list.getSelectedIndex (); list.remove (색인); MusicNames.Remove (this.index); } if (e.getSource () == bdElectTable) {// 목록을 지우겠습니다. removeall (); MusicNames.Removeall (MusicNames); player.stop (); 플레이어 = null; } // 재생 될 목록을 두 번 클릭하면 addmouseListener (new MouseAdapter () {public void mouseClicked (mouseevent e) {// double-click if (e.getClickCount () == 2) {if (player! = null) {player.stop (); }});} // "ControlLerListener"인터페이스가 구현 되었으므로이 방법은 미디어 플레이어에서 전송 된 이벤트를 처리하는 데 사용됩니다. public void controllerupdate (controlleervent e) {문자열 box = (string) select.getSelectedItem (); // 재생 순서를 판단합니다. if (e instancef endofmediaevent) {player.setmediatime (new Time (0)); if ( "단일 루프".equals (box)) {player.start (); } if ( "순차 재생".equals (box)) {nextMusic (); } if ( "shutter play".equals (box)) {if (this.musicNames! = null &&! this.musicNames.isempty ()) {int index = (int) rand.nextInt (this.musicNames.size ())+1; try {player = manager.createrealizedplayer (musicnames.get (index) .touri (). tourl ()); player.prefetch (); player.setMediatime (new Time (0.0)); // play player.addControllerListener (this); l.settext ( "재생 :"+this.musicNames.get (index) .toString ()); list.select (색인); player.start (); 플래그 = 1; } catch (noplayerException | can niclerealizeexception | ioexception e1) {e1.printstacktrace (); }}}}}}}} / *** mp3 노래 이름을 얻습니다** @mp3 파일 경로* @song name* / public string getMusicName (String Str) {int i; for (i = str.length () -1; i> 0; i-) {if (str.charat (i) == '//') break; } str = str.substring (i + 1, str.length () -4); Return str; } / *** 다음 구현 함수* / public void nextMusic () {} / *** 이전 구현 함수* / public void previouseMusic () {} / *** play mp3 main function* / public void playfile () {player = manager.createrealizedplayer (musicnames.get (index) (). player.prefetch (); player.setMediatime (new Time (0.0)); // play player.addControllerListener (this); l.setfont (새 글꼴 ( "宋体", 0,20)); l.settext ( "재생 :"+this.musicNames.get (index) .toString ()); // 재생중인 노래를 표시합니다. player.start (); Mythread11 TT = New Mythread11 (); tt.start (); } catch (예외 e1) {// 음악을 재생할 수 없을 때 DealError ()를 처리합니다. 반품; } this.setframe (); } public void setframe () {countsecond = (int) player.getDuration (). getSeconds (); timeslider.setmaximum (countsecond); timeslider.setValue (0); Newtime = 0; } private void dealError () {// todo 자동 생성 메소드 Stub MusicNames.remove (index); if (-count == index) index = 0; if (count == 0) player = null; else playfile (); }/*** MP3 파일 내부 클래스 필터링*/클래스 musicfilechooser는 jfilechooser {}/*** mp3 파일 필터링 보조 내부 클래스*/class myfileFilter fileFilter를 확장합니다 {// fileFilter는 추상 클래스입니다. 문자열 설명; public myfilefilter () {super (); } public myFileFilter (string [] suffarr, String Description) {super (); this.suffarr = subarr; this.descript = 설명; } public boolean accept (file f) {for (string s : suffarr) {if (f.getName (). toupperCase (). EndSwith (s)) {return true; }} return f.isdirectory (); } public String getDescription () {return this.dection; }}/*** 읽기 표시 시간 진행 막대*/public void run () {while (true) {sleep (); if (player! = null) {if (ispressing == 0) {if (ischanging == 1) {newtime = timeslider.getValue (); player.setMediatime (New Time (((Long) Newtime))*10000000000); ischanging = 0; } else {newTime = (int) player.getMediatime (). getSeconds (); timeslider.setValue (Newtime); TimeInformation.settext ( "현재 시간 :"+newtime/60+":"+newtime%60+"||"+"총 시간 :"+countsecond/60+":"+countsecond%60); }}}}}}}}}} // 가사를 구현하는 스레드 Mythread11은 스레드 {public void run () {// todo auto-auto-kenerated method stub try {lrc lrc = readlrc.readlrc ( "traveling light.lrc"); 가사 ls = parselrc.parselrc (lrc); 플레이 테스트 (LS); } catch (예외 e) {}}} 정적 무효 플레이 테스트 (가사 LS)는 InterruptedException {tp.setfont (new Font ( "宋体", 1,20)); tp.setforeground (color.blue); StyledDocument doc = tp.getStyledDocument (); SimpleAttributeset Center = New SimpleAttributeset (); styleconstants.setalignment (Center, Styleconstants.align_center); // show doc.setparagraphattributes (0, doc.getLength (), Center, False); tp.settext ( "아티스트 :" + ls.getar ()); tp.settext ( "앨범 :" + ls.getal ()); tp.settext ( "노래 :" + ls.getti ()); tp.settext ( "가사 제작 :" + ls.getby ()); for (lyric l : ls.getlyrics ()) {tp.settext (l.gettxt ()); Thread.Sleep (l.getTimesize ()); }}}V. 전체 테스트 결과
다음과 같이
플레이어에 대한 자세한 내용은 "Java Player Function"을 클릭하여 배우십시오.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.