JAVA图片浏览器的音乐播放,在切换下一首歌的时候,当前的歌还在播放,怎么解决?

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.awt.*;

public class HOME extends JFrame implements ActionListener, ListSelectionListener {
double height;
JLabel imageview = new JLabel();

JButton b1 = new JButton();
JButton profile_photo = new JButton();

JButton switch1 = new JButton("<");
JButton switch2 = new JButton(">");
JButton First = new JButton("首张");
JButton Last = new JButton("末张");
ImageIcon icon1 = null;
ImageIcon icon2 = null;

JPanel North = new JPanel();
JPanel South = new JPanel();
JPanel Center = new JPanel();
JPanel West = new JPanel();
JPanel East = new JPanel();
JFileChooser chooser = new JFileChooser();
JMenuBar menuBar = new JMenuBar();

JTextArea phototext = new JTextArea();
String photo_name;

// 文件列表
String Path = "./image";
File file = new File(Path);
File[] list = file.listFiles();
int index = 0;
/// 音乐播放
//音乐文件列表
String musicPath = "./music";
File musicfile = new File(musicPath);
File[] musiclist = musicfile.listFiles();
int index_music = 0;

JButton play = new JButton("播放");
JButton stop = new JButton("停止");
JButton playlast = new JButton("|<");
JButton playnext = new JButton(">|");
boolean isPlaying = false;
boolean isRestart = false;

Audio audio = new Audio();
// 菜单项
JMenuItem choosephoto = new JMenuItem("打开图片");

//图片列表
private String[] lists = { "111","222","333","444","555","666","777","888","999"};
JList photolist = new JList(list);

public HOME() {
    // 框架设置


    setTitle("图片浏览器");
    setLocation(300, 100);
    setSize(1300, 900);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    setLayout(new BorderLayout());

    //图片列表
    photolist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollpane = new JScrollPane(photolist);
    scrollpane .setPreferredSize(new Dimension(100,500)); //滚动条的大小即可调整列表长宽,如果想再加入一条横向滚动条,可设置列表的preferredSize

    // 组件添加
    North.setLayout(new BorderLayout());
    // 此处没有设置South的布局,因为设置后再将South面板放入框架中时,发现三个按钮无法全部加入,只能加入最后一个
    Center.setLayout(new BorderLayout());

    North.add(menuBar);
    add(North, BorderLayout.NORTH);
    Center.add(imageview);
    add(Center, BorderLayout.CENTER);
    West.add(scrollpane); //此处只需加入滚动条即可。不需要再加入photolist
    South.add(play);
    South.add(stop);
    South.add(playlast);
    South.add(playnext);
    South.add(switch1);
    South.add(switch2);
    South.add(First);
    South.add(Last);
    add(South, BorderLayout.SOUTH);
    add(East, BorderLayout.EAST);
    add(West, BorderLayout.WEST);

    // 监听器添加
    switch1.addActionListener(this);
    switch2.addActionListener(this);
    First.addActionListener(this);
    Last.addActionListener(this);
    play.addActionListener(this);
    stop.addActionListener(this);
    playlast.addActionListener(this);
    playnext.addActionListener(this);
    photolist.addListSelectionListener(this);


    // 图像设置
    // 头像/
    ImageIcon image_local1 = new ImageIcon("./image/头像.jpg");
    Image imageget1 = image_local1.getImage();
    Image finalimage1 = imageget1.getScaledInstance(100, 100, Image.SCALE_AREA_AVERAGING);
    icon1 = new ImageIcon(finalimage1);
    // 图片/

    // 组件设置
    lb1.setFont(new Font("宋体", Font.BOLD, 20));
    b1.setIcon(icon1);
    switch1.setVisible(true);
    switch2.setVisible(true);
    imageview.setIcon(icon2);
    imageview.setBounds(50, 50, 500, 500);
    phototext.setFont(new Font("宋体", Font.BOLD, 20));
    phototext.setEditable(false);


    Menu();

    // 线程启动
    audio.start();
    isPlaying = true;
}

public void Menu() {
    this.add(menuBar, BorderLayout.NORTH);
    this.setJMenuBar(menuBar);
    JMenu file = new JMenu("文件");
    JMenuItem photolist = new JMenuItem("图片列表");

    menuBar.add(file);
    menuBar.add(photolist);
    menuBar.add(phototext);
    menuBar.add(b1);
    file.add(choosephoto);

    setVisible(true);
    // 文件选择
    chooser.setCurrentDirectory(new File("./image"));
    choosephoto.addActionListener(this);
}


@Override
public void valueChanged(ListSelectionEvent e) {
    if(e.getSource() == photolist) {
        int index = photolist.getLeadSelectionIndex();
        phototext.setText("");
        photo_name = list[index].getPath();
        ImageIcon image_local2 = new ImageIcon(photo_name);
        Image imageget2 = image_local2.getImage();
        Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(),Image.SCALE_AREA_AVERAGING);
        icon2 = new ImageIcon(finalimage2);
        imageview.setIcon(icon2);
        imageview.setBounds(50, 50, 500, 500);
        File file = new File(list[index].getName());
        String filename = file.getName();
        double size = (file.length() / 1024.00);
        System.out.print(file.length());
        phototext.setText(filename + " (" + String.valueOf(size) + "KB)");

    }

}
private final Set<Long> THREADS = new HashSet<>();

public void someMethod () {
    if (THREADS.contains(Thread.currentThread().getId())) {
        throw new RuntimeException("该线程不能再调用这个方法");
    }
    THREADS.add(Thread.currentThread().getId());
    // 方法内容
}
public void actionPerformed(ActionEvent e) {
Runnable action = () ->{
    if (e.getSource() == switch1) {
        while (index <= list.length) {
            if (index == 0) {
                JOptionPane.showMessageDialog(West, "已经是第一张图", "提示", JOptionPane.WARNING_MESSAGE);
                break;
            } 
                index--;
                phototext.setText("");
                photo_name = list[index].getPath();
                ImageIcon image_local2 = new ImageIcon(photo_name);
                Image imageget2 = image_local2.getImage();
                Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(),
                        Image.SCALE_AREA_AVERAGING);
                icon2 = new ImageIcon(finalimage2);
                imageview.setIcon(icon2);
                imageview.setBounds(50, 50, 500, 500);
                File file = new File(list[index].getName());
                String filename = file.getName();
                double size = (file.length() / 1024.00);
                phototext.setText(filename + " (" + String.valueOf(size) + "KB)");
                break;
        }
    }
    if (e.getSource() == switch2) {
        while (index <= list.length) {
            if (index == list.length) {
                JOptionPane.showMessageDialog(West, "已经是最后一张图", "提示", JOptionPane.WARNING_MESSAGE);
            }
            phototext.setText("");
            photo_name = list[index].getPath();
            ImageIcon image_local2 = new ImageIcon(photo_name);
            Image imageget2 = image_local2.getImage();
            Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(),
                    Image.SCALE_AREA_AVERAGING);
            icon2 = new ImageIcon(finalimage2);
            imageview.setIcon(icon2);
            imageview.setBounds(50, 50, 500, 500);
            File file = new File(list[index].getName());
            String filename = file.getName();
            double size = (file.length() / 1024.00);
            phototext.setText(filename + " (" + String.valueOf(size) + "KB)");
            index++;
            break;
        }
    }
    if(e.getSource() == First) {
            index=0;

            phototext.setText("");
            photo_name = list[index].getPath();
            ImageIcon image_local2 = new ImageIcon(photo_name);
            Image imageget2 = image_local2.getImage();
            Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(),
                    Image.SCALE_AREA_AVERAGING);
            icon2 = new ImageIcon(finalimage2);
            imageview.setIcon(icon2);
            imageview.setBounds(50, 50, 500, 500);
            File file = new File(list[index].getName());
            String filename = file.getName();
            double size = (file.length() / 1024.00);
            phototext.setText(filename + " (" + String.valueOf(size) + "KB)");
    }
    if(e.getSource() == Last) {
        index=list.length-1;

        phototext.setText("");
        photo_name = list[index].getPath();
        ImageIcon image_local2 = new ImageIcon(photo_name);
        Image imageget2 = image_local2.getImage();
        Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(),
                Image.SCALE_AREA_AVERAGING);
        icon2 = new ImageIcon(finalimage2);
        imageview.setIcon(icon2);
        imageview.setBounds(50, 50, 500, 500);
        File file = new File(list[index].getName());
        String filename = file.getName();
        double size = (file.length() / 1024.00);
        phototext.setText(filename + " (" + String.valueOf(size) + "KB)");
}

    if (e.getActionCommand() == "打开图片") {
        int choose = chooser.showOpenDialog(null);
        if (choose == JFileChooser.APPROVE_OPTION) {
            phototext.setText("");
            photo_name = chooser.getSelectedFile().getName();
            ImageIcon image_local2 = new ImageIcon(photo_name);
            Image imageget2 = image_local2.getImage();
            Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(),
                    Image.SCALE_AREA_AVERAGING);
            icon2 = new ImageIcon(finalimage2);
            imageview.setIcon(icon2);
            imageview.setBounds(50, 50, 500, 500);
            File file = new File(chooser.getSelectedFile().getName());
            String filename = file.getName();
            double size = (file.length() / 1024.00);
            phototext.setText(filename + " (" + String.valueOf(size) + "KB)");
        }
    }
    if (e.getActionCommand() == "播放") {
        String filePath = "./music";
        try {
            System.out.print("运行了");
            Runnable play = ( ) ->{
            audio.run();
            };
            Thread t1 = new Thread(play);
            t1.start();
            isPlaying = true;
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }
    if (e.getSource() == stop) {
        try {
            System.out.print("停止了");

            isPlaying = false;
            isRestart  = false;
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }
    if (e.getSource() == playnext) {

        try {
            System.out.print("下一个");

            isPlaying = false;

            Runnable r =() ->{
                try {
                    someMethod();
                    index_music++;
                    isRestart = true;
                    audio.restart();

                } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            };
            Thread t = new Thread(r);
            t.start();

        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }
    if (e.getSource() == playlast) {
        try {
            if(index_music == 0) {
                JOptionPane.showMessageDialog(West, "已经是第一首背景音乐", "提示", JOptionPane.WARNING_MESSAGE);
            }
            isPlaying = false;
            isRestart = true;
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }
};
Thread act = new Thread(action);
act.start();

}


public class Audio extends Thread {

    public Audio() {

    }

    public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println(e.toString());
            }

            if (isPlaying) {
                try {
                    System.out.print("启动了");
                    player();
                } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
                    e.printStackTrace();
                }
            }

    }
    public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        if(isRestart) {
            System.out.print("测试了~?");
            isPlaying =true;
            player();

        }
    }
    // 取得文件输入流
    private void player() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        AudioInputStream audioInputStream;// 文件流

        AudioFormat audioFormat;// 文件格式

        SourceDataLine sourceDataLine;// 输出设备

        String musicname = musiclist[index_music].getName();
        File file = new File("./music/"+musicname);


        audioInputStream = AudioSystem.getAudioInputStream(file);

        audioFormat = audioInputStream.getFormat();

        // 转换文件编码

        if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {

            audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,

                    audioFormat.getSampleRate(), 16, audioFormat.getChannels(),

                    audioFormat.getChannels() * 2, audioFormat.getSampleRate(),

                    false);

            audioInputStream = AudioSystem.getAudioInputStream(audioFormat,

                    audioInputStream);

        }

        // 打开输出设备

        DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,

                audioFormat, AudioSystem.NOT_SPECIFIED);

        sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

        sourceDataLine.open(audioFormat); // 打开具有指定格式的行,这样可以使行获得所有所需的系统资源并变得可操作

        sourceDataLine.start(); // 允许某一数据行执行数据I/O

        byte tempBuffer[] = new byte[320];

        try {

            int cnt;

            // 读取数据到缓存区

            // 从音频流读取指定的最大数量的数据字节,并将其放入给定的字节数组中。

            // return: 读入缓冲区的总字节数;如果因为已经到达流末尾而不再有更多数据,则返回-1

            while ((cnt = audioInputStream.read(tempBuffer, 0,tempBuffer.length)) != -1 &&isPlaying) {

                if (cnt > 0) {

                    // 写入缓存数据

                    sourceDataLine.write(tempBuffer, 0, cnt); // 通过此源数据行将音频数据写入混频器

                }

            }

            // Block等待临时数据被输出为空

            // 通过在清空数据行的内部缓冲区之前继续数据I/O,排空数据行中的列队数据

            sourceDataLine.drain();

            // 关闭行,指示可以释放的该行使用的所有系统资源。如果此操作成功,则将行标记为 closed,并给行的侦听器指派一个 CLOSE 事件。

            sourceDataLine.close();

        } catch (Exception e) {

            e.printStackTrace();

            System.exit(0);

        }
    }
}
public static void main(String[] args) {
    Runnable h = () ->{
    HOME home = new HOME();
    };
    Thread t = new Thread(h);
    t.start();
}

}


```playnext那一部分是切下一首歌,但是切了后当前的歌曲仍在播放,怎么解决
查看全部
weixin_44041739
A.NinjaCatDavid
2019/05/03 17:24
  • java
  • 点赞
  • 收藏
  • 回答
    私信

0个回复