English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

تعليمك كيفية إنتاج مشغل الموسيقى Java بسهولة

أولاً: مبدأ تنفيذ مشغل الموسيقى

 وظائف multimedi في Java ضعيفة جدًا، لذا هناك مكتبة خاصة بمعالجة multimedi تُدعى JMF، يمكن تقسيم نماذج التي يقدمها JMF إلى سبعة فئات تقريبًا

* مصدر البيانات (Data source)
* جهاز التقاط (Capture Device، يشمل تقاطع الفيديو والصوت)
* مشغل (Player)
* معالج (Processor)
* خزان البيانات (DataSink)
* تنسيق البيانات (Format)
* مدير (Manager)

أما المプレير الموسيقي الذي أنشأته أنا MyMusicPlayer (وهذا هو اسم الكلاس الذي أنشأته) فهو يستخدم كلاس Player في JMF لتحقيق وظائف التشغيل وأكثر من ذلك.

أولاً، يجب علينا تثبيت JMF. عملية تثبيت JMF، على الأرجح، ستكون مصدر إزعاج كبير للكثير من المبتدئين، حيث يدعم JMF إصدارات JDK 32 بت فقط، ومع ذلك، يجب أن تكون بيئة IDE مثل Eclipse متوافقة مع JDK، أي أن بيئة IDE يجب أن تدعم إصدارات JDK 32 بت. بعد تثبيت JMF، قد لا يتم تشغيل MP3 بنجاح دائمًا، ويجب أيضًا تثبيت mp3plugin لـ JMF.

النقطة الثانية: صورة واجهة المستخدم

النقطة الثالثة: رسم تخطيط الهيكل الوظيفي

النقطة الرابعة: كود تنفيذ الوظائف المختلفة

public class MyMusicPlayer implements ActionListener, ControllerListener,Runnable{
 JFrame j=new JFrame("مشغل الموسيقى");
 JLabel TablePlaer=new JLabel("قائمة اللعب");
 JButton BAdd=new JButton("إضافة أغنية");
 JButton BDelect=new JButton("حذف الأغنية");
 JButton BDelectTable=new JButton("إزالة القائمة");
 JButton BMoveNext=new JButton("الشريط التالي");
 JButton BMovePrevious=new JButton("الشريط السابق");
 JButton BPlayer=new JButton("إيقاف");
 JButton BStop=new JButton("停止");
 JButton BSet=new JButton("عرض النصوص");
 JButton BEnd=new JButton("停止");
 String[] s={"顺序播放","单曲循环","随机播放"};        //مجموعة خيارات قائمة التنازل
 JComboBox select=new JComboBox(s);          //إنشاء خيار تنازلي
 JPanel p1=new JPanel();           //منطقة قائمة اللعب
 JPanel p=new JPanel(); 
 JPanel p2=new JPanel();           //منطقة الأزرار
 JPanel p3=new JPanel(); 
 JLabel l=new JLabel(); 
 JPanel p5=new JPanel(); //موضع قائمة اللعب
 JPanel p6=new JPanel(); //موضع اسم الأغنية التي تعزف
 static JPanel pp=new JPanel();
 static JLabel lb;
 public static JTextArea jt=new JTextArea();
 static int index;  //播放列表的下标
 int count;
 int flag;   //标记是随机播放还是顺序播放
 int countSecond; //获取音乐的总时间值
 static int newtime = 0;
 int ischanging = 0; //当鼠标是对游标进行点击,进度值也会改变
 int ispressing = 0; //判断鼠标是否对游标进行点击
 File MusicName = null;
 static java.util.List<File> MusicNames = null; //运用泛型,创建File对象
 File currentDirectory = null;
 List list; // 文件列表
 FileDialog open; // 定义文件对话框对象
 Random rand = new Random();
 String filename;
 // 进度条
 JButton timeInformation = new JButton();
 JSlider timeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 100, 0); // (SwingConstants.HORIZONTAL)用于定向进度条为水平方向的常量的集合
                     // (0, 100, 0)用指定的最小值、最大值和初始值创建一个水平滑块。
 // 播放
 Player player = null; 
 MusicFileChooser fileChooser = new MusicFileChooser();
 static JTextPane tp=new JTextPane();  //显示歌词区域
 static JTextArea are=new JTextArea(); //显示图片区域
 public MyMusicPlayer(){
  j.setSize(1200, 700);
  j.setLayout(null);
  j.getContentPane().setBackground(Color.BLACK);
  j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  p.setBounds(2, 563, 1180, 95)}
  p.setLayout(new BorderLayout());
  p1.setBounds(2, 3, 298, 30);   
  p1.setBackground(new Color(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.setBackground(new Color(255, 255, 255));
  p5.setBounds(2, 35, 298, 526);
  p5.setLayout(null);
  p5.setBackground(new Color(255, 255, 255));
  p6.setBounds(301, 3, 880, 30);
  p6.setLayout(null);
  p6.setBackground(new Color(255, 255, 255));
  l.setBounds(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(new Color(255, 255, 255));
  tp.setBounds(301, 35, 880, 49);
  pp.add(are);
  pp.add(lb);
  // قائمة الملفات
  list = new List(10);
  list.setBounds(100, 55, 187, 495); //列表区域
  list.addActionListener(this);
  j.add(list);
  j.add(jt);
  j.add(tp);
  BAdd.setBounds(5,20, 90,30);
  BAdd.setBackground(new Color(255,255,255));
  BDelect.setBounds(5, 80, 90, 30);
  BDelect.setBackground(new Color(255,255,255));
  BDelectTable.setBounds(5, 140, 90, 30);
  BDelectTable.setBackground(new Color(255,255,255));
  TablePlaer.setBounds(30, 100, 200, 50);
  TablePlaer.setFont(new Font("宋体",1, 20));
  p1.add(TablePlaer);
  BMovePrevious.setBackground(new Color(255,255,255));
  BPlayer.setBackground(new Color(255,255,255));
  BMoveNext.setBackground(new Color(255,255,255));
  BStop.setBackground(new Color(255,255,255));
  select.setBackground(new Color(255,255,255));
  BSet.setBackground(new Color(255,255,255));
  p2.add(BMovePrevious);
  p2.add(BPlayer);
  p2.add(BMoveNext);
  p2.add(BStop);
  p2.add(select);
  p2.add(BSet);
  p2.setBackground(new Color(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);
   /*
   * Implement progress bar
   /* */ 
   timeSlider.setMajorTickSpacing(1); // Call this method to set the interval of the main tick marks. The number passed in represents the distance measured in values between each main tick mark.
   timeSlider.setPaintTicks(true); // To draw the main ticks, setPaintTicks must be set to true
   timeSlider.addChangeListener(new ChangeListener() { // Create a new ChangeListener and add it to the slider.
    public void stateChanged(ChangeEvent arg0) {
     if (player != null && ispressing == 1) {
      newtime = (int)((JSlider)arg0.getSource()).getValue();
      timeInformation.setText("当前时间:"+newtime/60+":"+newtime%60+"  ||  "+" 总时间: "+countSecond/60+":"+countSecond%60);
      ischanging = 1;
     }
    }
   });
   timeSlider.addMouseListener(new MouseAdapter(){
    public void mousePressed(MouseEvent arg0) {
     ispressing = 1;   //当鼠标对游标进行点击时
    }
    public void mouseReleased(MouseEvent arg0) {
     ispressing = 0;   //当鼠标不对游标进行点击时
    }
   });
   timeInformation.setText("当前时间:00:00  ||  总时间:00:00");
   timeInformation.setBackground(new Color(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) throws IOException, InterruptedException { //InterruptedException:当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常
  MyMusicPlayer play=new MyMusicPlayer();
  Thread timeRun = new Thread(play);
  timeRun.start(); 
 }
 @Override
 public void actionPerformed(ActionEvent e) {
  String cmd = e.getActionCommand();     //通过获取字符串来判断是播放还是暂停,
  String box = (String) select.getSelectedItem();   //تحديد ترتيب اللعب
  if(e.getSource()==BAdd)
  {
   if (player == null) {
    if (fileChooser.showOpenDialog(j) == MusicFileChooser.APPROVE_OPTION) {
     this.MusicName = fileChooser.getSelectedFile();
     File cd = fileChooser.getCurrentDirectory(); //الحصول على المسار الحالي
     if (cd != this.currentDirectory|| this.currentDirectory == null) {
      FileFilter[] fileFilters = fileChooser.getChoosableFileFilters(); //FileFilter هو فئة抽象ة، يستخدمها JFileChooser لتصفية مجموعة الملفات المعروضة للمستخدم
      File files[] = cd.listFiles(); //cd.listFiles() يعني العودة إلى مجموعة من أسماء المسارات، هذه الأسماء تعبر عن الملفات في هذا المسار المعبّر عنه
      this.MusicNames = new ArrayList<File>();
      for (File file : files) { //في كل دورة يتم تعيين عنصر الصف من مجموعة الصفوف إلى هذا المتغير، ثم يتم تنفيذ العمليات على هذا المتغير في جسم الدورة مثل:
             //for(int i=0;i<files.length;i++){ file = files[i];……}
       filename = file.getName().toLowerCase();   //الحصول على جميع أسماء الموسيقى
       for (FileFilter filter : 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("إيقاف");
   player.start();
  }
  if(e.getSource()==BStop){   // التوقف
    if (player != null) {
     player.stop();
     timeInformation.setText("وقت الحالي:00:00  ||  إجمالي الوقت:00:00");
     timeSlider.setValue(0);
     player.setMediaTime(new Time(0)); //إعداد الوقت إلى الصفر
  }
    }
  if(e.getSource()==BMoveNext){  //الأغنية التالية
    if (player != null) {
     if("شغيل متسلسل".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()) {
          index=(int) rand.nextInt(this.MusicNames.size())+1;
         }
         player.stop();   //إذا تم النقر على الأغنية السابقة، فتوقف الأغنية الحالية عن اللعب وتشغيل الأغنية السابقة
         try {
          player = Manager.createRealizedPlayer(MusicNames.get(index).toURI().toURL());
          player.prefetch();
          player.setMediaTime(new Time(0.0));// 从某个时间段开始播放
          player.addControllerListener(this);
          l.setText("جاري اللعب: " + this.MusicNames.get(index).toString());
          list.select(index);
          player.start(); 
          flag=1;
         } catch (NoPlayerException | CannotRealizeException | IOException e1) {
          e1.printStackTrace();
         }
       }
     }
    }
  }
  if(e.getSource()==BMovePrevious){  //الأغنية السابقة
    if (player != null) {
     if("شغيل متسلسل".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.MusicNames.size() - 1;
       }
       player.stop();    //إذا تم النقر على الأغنية السابقة، فتوقف الأغنية الحالية عن اللعب وتشغيل الأغنية السابقة
       try {
        player = Manager.createRealizedPlayer(MusicNames.get(index).toURI().toURL());
        player.prefetch();
        player.setMediaTime(new Time(0.0));// 从某个时间段开始播放
        player.addControllerListener(this);
        l.setText("جاري اللعب: " + this.MusicNames.get(index).toString());
        list.select(index);
        player.start(); 
        flag=1;
       } catch (NoPlayerException | CannotRealizeException | IOException e1) {
        e1.printStackTrace();
       }
      }
    }
    }
  }
  if(e.getSource()==BDelect){    //حذف الأغنية
   index =list.getSelectedIndex();
   list.remove(index);
   MusicNames.remove(this.index);
  }
  if(e.getSource()==BDelectTable){   //تفريغ القائمة
   list.removeAll();
   MusicNames.removeAll(MusicNames);
   player.stop();
   player = null;
  }
  // تنفيذ تشغيل الموسيقى عند النقر المزدوج على القائمة
  list.addMouseListener(new MouseAdapter() {
   public void mouseClicked(MouseEvent e) {
    // معالجة عند النقر المزدوج
    if (e.getClickCount() == 2) {
     if(player!=null){
      player.stop();
     }
     // يلعب الملف المحدد
     index=list.getSelectedIndex();
     PlayFile();
    } 
   }
  });
}
 // طالما تم تحقيق واجهة "ControllerListener"، يستخدم هذا الطريقة لمعالجة أحداث مشغل الوسائط المرسلة؛
 public void controllerUpdate(ControllerEvent e) {
  String box = (String) select.getSelectedItem();   //تحديد ترتيب اللعب
  if (e instanceof EndOfMediaEvent) {
   player.setMediaTime(new Time(0));
   if ("تكرار الأغنية".equals(box)) {
    player.start();
   }
   if("شغيل متسلسل".equals(box)){
    nextMusic();
   }
   if("شغيل عشوائي".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));// 从某个时间段开始播放
        player.addControllerListener(this);
        l.setText("جاري اللعب: " + this.MusicNames.get(index).toString());
        list.select(index);
        player.start(); 
        flag=1;
       } catch (NoPlayerException | CannotRealizeException | IOException e1) {
        e1.printStackTrace();
       }
     }
   }
  }
 }
  */
  * الحصول على اسم أغنية MP3
  * 
  * @مسار ملف MP3
  * @اسم الأغنية
  */
 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 PreviousMusic() {
 }
 */
  * تنفيذ دالة رئيسية للاعتماد على ملف MP3
  */
 public void PlayFile() {
  try {
   player = Manager.createRealizedPlayer(MusicNames.get(index).toURI().toURL());
   player.prefetch();
   player.setMediaTime(new Time(0.0));// 从某个时间段开始播放
   player.addControllerListener(this);
   l.setFont(new Font("宋体",0,20));
   l.setText("正在播放:"+this.MusicNames.get(index).toString()); //显示正在播放的歌曲
   list.select(index);
   player.start();
   Mythread11 tt=new Mythread11();
   tt.start();
  } catch (Exception e1) { //当选到一首音乐不能播放时,对其进行处理
   dealError();
   return;
  }
  this.setFrame();
  }
 public void setFrame()
 {
  countSecond = (int)player.getDuration().getSeconds();
  timeSlider.setMaximum(countSecond);
  timeSlider.setValue(0);
  newtime = 0;
 }
private void dealError() {  
  // TODO 自动生成的方法存根
 MusicNames.remove(index);
 if( --count == index )
  index = 0;
 if( count == 0)
  player = null;
 else
  PlayFile();
 }
*/
 * MP3文件筛选内部类
 */
class MusicFileChooser extends JFileChooser {
 }
*/
 * MP3文件筛选辅助内部类
 * 
 */
class MyFileFilter extends FileFilter { //FileFilter 是一个抽象类,JFileChooser 使用它过滤显示给用户的文件集合
 String[] suffarr;
 String description;
 public MyFileFilter() {
  super();
 }
 public MyFileFilter(String[] suffarr, String decription) {
  super();
  this.suffarr = suffarr;
  this.decription = decription;
 }
 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.decription;
 }
}
*/
 * 读取显示时间进度条
 */
public void run() {
 while(true) {
  sleep();
  if(player != null) {
   if(ispressing == 0) {
    if(ischanging == 1) {
     newtime = timeSlider.getValue();
     player.setMediaTime(new Time(((long)newtime)*1000000000));
     ischanging = 0;
    } else {
     newtime = (int)player.getMediaTime().getSeconds();
     timeSlider.setValue(newtime);
     timeInformation.setText("当前时间:"+newtime/60+":"+newtime%60+"  ||  "+" 总时间: "+countSecond/60+":"+countSecond%60);
    }
   }
  }
 }
}
// 实现歌词的线程
class Mythread11 extends Thread { 
 public void run() {
  // TODO 自动生成的方法存根
  try{
   LRC lrc = ReadLRC.readLRC("Traveling Light.lrc"); 
   Lyrics ls = ParseLRC.parseLRC(lrc); 
   playTest(ls);
  catch(Exception e){
  }
 }
}
static void playTest(Lyrics ls) throws 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);  //عرض منطقة النصوص
 doc.setParagraphAttributes(0, doc.getLength(), center, false);
 tp.setText("الفنان: " + ls.getAr());
 tp.setText("البند: " + ls.getAl());
 tp.setText("الأغنية: " + ls.getTi());
 tp.setText("صنع النصوص: " + ls.getBy());
 للفوز (Lyric l : ls.getLyrics()) {
  tp.setText(l.getTxt());
  Thread.sleep(l.getTimeSize());
 }
}
}

الاختبار العام الخامس

كما يلي

للتعرف على المزيد عن مشغلات الأغاني، يرجى الضغط على 'وظائف مشغل الأغاني' للتعلم.

هذا هو كل محتوى المقالة، آمل أن يكون هذا المقال مفيدًا جدًا في تعلمكم، وآمل أيضًا أن تحصلوا على دعمكم لمقالة تعليمية تنادي.

أنت قد تحب