Home Java javaTutorial Implementation example of Java music player

Implementation example of Java music player

Sep 22, 2017 am 11:46 AM
java Example player

这篇文章主要介绍了java 实现音乐播放器的简单实例的相关资料,希望通过本文能帮助到大家,实现这样的功能,需要的朋友可以参考下

java 实现音乐播放器的简单实例

实现效果图:

代码如下


package cn.hncu.games;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.net.URL;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class MusicPlayer extends JFrame{
  //显示(歌曲名称)播放状态的标签
  JLabel songNameLabel = null;

  //四个播放功能键按钮
  JButton btnLast = null; //上一曲
  JButton btnPlay = null; //播放/停止
  JButton btnNext = null; //下一曲
  JButton btnLoop = null; //循环

  //歌曲列表
  JList songsList = null;
  AudioClip songs[] = null;
  AudioClip currentSong = null;
  int index=0; //当前歌曲在JList中的位置(序号)
  //歌曲文件名数组---String
  String[] strSongNames={ "song1.wav","song2.wav","song3.wav","song4.wav","song5.wav","song6.wav" };
  final String DIR="songs\\";

  //播放音乐的线程
  Thread playerThread=null;
  boolean isPlayOrStop = true;//true代表播放状态
  boolean isLoop = false; //是否为循环状态

  public MusicPlayer() {
    super("音乐播放器");
    setBounds(300, 50, 310, 500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(null);
    //hello();

    //显示(歌曲名称)播放状态的标签
    songNameLabel = new JLabel();
    Font songNameFont = new Font("黑体",Font.ITALIC,18);
    songNameLabel.setFont(songNameFont);
    songNameLabel.setText("我的音乐播放器");
    songNameLabel.setBounds(10, 10, 300, 40);
    getContentPane().add(songNameLabel);

    //四个播放功能键按钮
    btnLast = new JButton();
    btnPlay = new JButton();
    btnNext = new JButton();
    btnLoop = new JButton();
    //位置大小
    btnLast.setBounds(10, 70, 50, 40);
    btnPlay.setBounds(70, 70, 50, 40);
    btnNext.setBounds(130, 70, 50, 40);
    btnLoop.setBounds(190, 70, 50, 40);
    //设置图片
    btnLast.setIcon( new ImageIcon("images2/1.png"));
    btnPlay.setIcon( new ImageIcon("images2/2.png"));
    btnNext.setIcon( new ImageIcon("images2/3.png"));
    btnLoop.setIcon( new ImageIcon("images2/4.png"));
    //添加到框架
    getContentPane().add(btnLast);
    getContentPane().add(btnPlay);
    getContentPane().add(btnNext);
    getContentPane().add(btnLoop);
    //添加监听
    MyMouseListener mml = new MyMouseListener();
    btnLast.addMouseListener(mml);
    btnPlay.addMouseListener(mml);
    btnNext.addMouseListener(mml);
    btnLoop.addMouseListener(mml);


    //歌曲列表的标题
    JLabel listLabel = new JLabel("播放列表");
    listLabel.setBounds(10, 120, 100, 30);
    Font listLabelFont = new Font("黑体",Font.BOLD,16);
    listLabel.setFont(listLabelFont);
    getContentPane().add(listLabel);

    //歌曲列表
    /*
    songsList = new JList();
    songsList.setBounds(10, 150, 250, 300);
    songsList.setBackground(Color.CYAN);
    //把所有歌曲名逐个添加到List中
    //songsList.setListData(strSongNames);
    for(int i=0;i<strSongNames.length;i++){
      DefaultListModel dm = (DefaultListModel)songsList.getModel();
      dm.add(i,strSongNames[i]);
    }
    getContentPane().add(songsList);
    */

    DefaultListModel lm = new DefaultListModel();
    songsList = new JList(lm);
    songsList.setBounds(10, 150, 250, 300);
    songsList.setBackground(Color.CYAN);
    //把所有歌曲名逐个添加到List中
    //songsList.setListData(strSongNames);
    songs = new AudioClip[strSongNames.length];
    for(int i=0;i<strSongNames.length;i++){
      lm.add(i,strSongNames[i]);
      songs[i] = loadSound(strSongNames[i]);
    }
    getContentPane().add(songsList);
    //lm.remove(3);

    //对JList控件的监听技术实现
    songsList.addListSelectionListener(new ListSelectionListener() {
      @Override
      public void valueChanged(ListSelectionEvent e) {
        currentSong.stop();
        index = songsList.getSelectedIndex();
        isPlayOrStop = true;
        playerThread = new Thread( new MusicRun() );
        playerThread.start();
      }
    });


    //单开一个线程,专用于播放音乐
    playerThread = new Thread( new MusicRun() );
    playerThread.start();


    setVisible(true);
  }



  private AudioClip loadSound(String fileName) {
    try {
      URL url = new URL("file:songs\\"+fileName);
      AudioClip au = Applet.newAudioClip(url);
      return au;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


  //讲解音乐播放的基本技术
  private void hello() {
    try {
      File f = new File("songs\\song1.wav");
      URL url = f.toURI().toURL();
      //URL url = new URL("file:songs\\song1.wav");
      AudioClip au = Applet.newAudioClip(url);
      au.play();
      //au.loop();
      //au.stop();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private class MyMouseListener extends MouseAdapter{
    @Override
    public void mouseClicked(MouseEvent e) {
      JButton btn = (JButton) e.getSource();
      currentSong.stop();
      if(btn==btnPlay){
        isPlayOrStop = !isPlayOrStop;
      }else if(btn==btnLast){
        index--;
        if(index<0){
          index = strSongNames.length-1;
        }
        //isPlayOrStop=true;
      }else if(btn==btnNext){
        index++;
        index = index%strSongNames.length;

      }else if(btn==btnLoop){
        isLoop = !isLoop;
      }

      if(isPlayOrStop){//播放
        playerThread = new Thread( new MusicRun() );
        playerThread.start();
      }else{//停止
        songsList.setSelectedIndex(index);
        songNameLabel.setText("停止播放:"+strSongNames[index]);
        btnPlay.setIcon( new ImageIcon("images2/2.png"));
      }
    }
  }

  private class MusicRun implements Runnable{
    @Override
    public void run() {
      currentSong = songs[index];
      if(isLoop){
        currentSong.loop();
        songNameLabel.setText("循环播放:"+strSongNames[index]);
      }
      if (isPlayOrStop) {
        currentSong.play();
      }
      //在播放列表中选定当前歌曲
      songsList.setSelectedIndex(index);
      //把播放按钮的图标切换成“停止”
      btnPlay.setIcon( new ImageIcon("images2/5.png"));

      if(!isLoop){
        songNameLabel.setText("正在播放:"+strSongNames[index]);
      }
    }
  }
public static void main(String[] args) {
    new MusicPlayer();
  }
}
Copy after login

The above is the detailed content of Implementation example of Java music player. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles