MP3播放器以及对音频的剪辑

由于原生的Java类库中所支持的音频是不支持MP3格式的,会直接放不出来所以改使用MP3Player.可以直接支持MP3文件的播放

可以直接实现文件的选择和音频的剪辑功能

package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;

import player.PlayTest;
import search_and_download.FileManager;
import song.Song;

public class Client extends JFrame{
    private int lineNum;   //记录当前行数
    private String[] lineContent; //文本文件行数组
    private String content;
    private ArrayList<String> pausingFlag = new ArrayList<String>();  //时间--断句标记节点
    private ArrayList<Integer> stopeTimeOfLentth = new ArrayList<Integer>(); //数字断点标记--时长
    private ArrayList<Integer> stopTimeOfNum = new ArrayList<Integer>();  //数字断点标记
    private float mp3Length;
    public JTextArea textArea;   //txt文本文件显示域  将文本域改为JList
    public JTextArea outPutPath; //输出文件的路径
    private JTextField searchText;
    private PlayTest player;
    private JList musicList;   //歌曲列表
    private JList lycList;     //歌词列表
    private JButton openButton;
    private JSlider js;
    private int time;
    private int state;
    private long begintime;
    JTextArea jTextArea1;
    JTextArea jTextArea2;
    private JFileChooser chooser = new JFileChooser(); // 创建一个文件选择器
    private int stopTime; //记录时间
    public String mp3FilePath;  //mp3文件路径
    public String txtFilePath;  //txt文件路径
    private ArrayList<Song> songlist;// musicList对应的Song列表
    private ArrayList<String> stringlist;// songlist对应的字符串列表
    private ArrayList<String> lyclist = new ArrayList<String>();   //译文对应的字符串列表
    

    @SuppressWarnings("unchecked")
    private void go() {
        pausingFlag.add("00:00:00.000");
        JPanel mainPanel = new myPanel();
        // 歌曲列表组件
        musicList = new JList(getMusicList().toArray());
        musicList.setBackground(new Color(205, 205, 205, 0));
        musicList.setOpaque(false);
        musicList.setBorder(BorderFactory.createTitledBorder("本地歌曲列表   共"
                + stringlist.size() + "首"));
        musicList.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
                
            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            //鼠标移出窗口
            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseClicked(MouseEvent e) {
                // TODO Auto-generated method stub
                if (e.getClickCount() == 2){ 
                    
                    if (state == 0){
                        if(pausingFlag!=null && pausingFlag.size()>1 ){
                            pausingFlag.clear();
                            pausingFlag.add("00:00:00.000");
                            stopTime = 0;
                        }
                        if(stopeTimeOfLentth !=null && stopeTimeOfLentth.size()>0){
                            stopeTimeOfLentth.clear();
                        
                    }
                   }
                        playmusic(0, true);
                        //mp3FilePath = musicList.getm
                }
                }
            
        });
        
        musicList.setFixedCellWidth(550);
        musicList.setVisibleRowCount(3);
        // 歌曲列表滚动条
        JScrollPane qScroller = new JScrollPane(musicList);
        qScroller.setOpaque(false);
        qScroller.getViewport().setOpaque(false);
        qScroller
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        qScroller
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        
        
        //添加词句List
        lycList = new JList(getLycList().toArray());
        lycList.setBackground(new Color(205, 205, 205, 0));
        lycList.setOpaque(false);
        lycList.setBorder(BorderFactory.createTitledBorder("译文列表"));
        lycList.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
                
            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            //鼠标移出窗口
            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseClicked(MouseEvent e) {
                // TODO Auto-generated method stub
                if (e.getClickCount() == 2){ 
                    try {
                        int s = lycList.getSelectedIndex();  
                        int  f = stopTimeOfNum.get(s-1);
                        replayMusic(f * 40, true);
                        System.out.println(f*40);
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        replayMusic(0, true);
                    }
                }
             }
        });
        lycList.setFixedCellWidth(550);
        lycList.setVisibleRowCount(10);
        JScrollPane lScroller = new JScrollPane(lycList);
        lScroller.setOpaque(false);
        lScroller.getViewport().setOpaque(false);
        lScroller
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        lScroller
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        //打开选择txt文件
        JButton txtButton = new JButton("TXT");
        txtButton.addActionListener(new txtButtonActionListener());
        
        openButton = new JButton("MP3");
        openButton.setEnabled(false);
        openButton.addActionListener(new openButtonActionListener());
         
        JButton cleanButton = new JButton("CLEAN");
        cleanButton.addActionListener(new cleanButtonActionListener());
        //text文本显示域
        textArea = new JTextArea();
        textArea.setEditable(true);
        textArea.setColumns(50);
        textArea.setRows(10);
        //text滚动条
        JScrollPane scroll = new JScrollPane(textArea); 
        scroll.setOpaque(false);
        scroll.getViewport().setOpaque(false);
        scroll.setHorizontalScrollBarPolicy( 
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
        scroll.setVerticalScrollBarPolicy( 
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
        // 播放按钮
        JButton playButton = new JButton("Play");
        playButton.addActionListener(new playButtonActionListener());
        // 停止按钮
        JButton stopButton = new JButton("S/P");
        stopButton.addActionListener(new stopButtonActionListener());
        
        //保存按钮
        JButton cutButton = new JButton("Cut");
        cutButton.addActionListener(new cutButtonActionListener());
        // 进度条
        js = new JSlider();
        js.setPreferredSize(new Dimension(400,16));
        js.addMouseListener(new myMouseListener());
        js.setValue(0);
        // 进度显示
        jTextArea1 = new JTextArea("00:00");
        jTextArea2 = new JTextArea("00:00");

        outPutPath = new JTextArea();
        outPutPath.setColumns(50);
        outPutPath.setEditable(false);
        mainPanel.add(txtButton);
        mainPanel.add(openButton);
        mainPanel.add(cleanButton);
        mainPanel.add(qScroller);
        mainPanel.add(scroll);
        mainPanel.add(lScroller);
        mainPanel.add(jTextArea1);
        mainPanel.add(js);
        mainPanel.add(jTextArea2);
        mainPanel.add(stopButton);
        mainPanel.add(cutButton);
        mainPanel.add(outPutPath);

        // 整体框架设置
        JFrame frame = new JFrame("MP3播放器");
        frame.setIconImage(Toolkit.getDefaultToolkit()
                .getImage("pic\\icon.jpg"));
        frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        frame.setSize(600, 600);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    
    private ArrayList<String> getMusicList() {
        stringlist = new ArrayList<String>();
        FileManager.logRead();
        songlist = FileManager.locallist;
        for (int i = 0; i < FileManager.locallist.size(); i++) {
            Song so = songlist.get(i);
            stringlist.add(so.getName() + "	   " + so.getArtist_name());
        }
        return stringlist;
    }
    
    private ArrayList<String> getLycList() {
        if(lyclist.size()!= 0){
            lyclist.clear();
        }
        if(textArea !=null && textArea.getText()!=""){
            String s[] = textArea.getText().split("\n");
            for (int i = 0; i < s.length; i++) {
                if(s[i].contains("--->")){
                    lyclist.add(s[i]); 
                }
            }
        }
        
        return lyclist;
        
    }

    
    public static void main(String[] args) {
        Client client = new Client();
        client.go();
        // client.test();
    }

    private class myMouseListener implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub
            
        }

        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub
            player.state = -1;
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub
            
            //当前进度条的时间
            int t = js.getValue();
            long n = System.currentTimeMillis();
            begintime = n - t;
            //if(stopTime)
            playmusic(t / 25, true);
            player.state = 1;
        }

    }

    
    //txt按钮事件监听,选择TXT文件
    private class txtButtonActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            File file = null;
            String fileName = "";
            txtFilePath = "";
            int value = chooser.showOpenDialog(chooser);// 接受文件选择器的状态
            if (value == chooser.APPROVE_OPTION) {
                file = chooser.getSelectedFile();// 返回选中文件
                fileName = file.getName();
                txtFilePath = file.getPath();
                //System.out.println("选中的文件名:"+fileName);
                //System.out.println("选中文件路径:"+txtFilePath);
                String s;
                try {
                    s = getTxtContent(txtFilePath);
                    textArea.setText("");
                    textArea.append("00:00:00.000--->"+s);
                    lineContent = textArea.getText().split("\n");
                    openButton.setEnabled(true);
                    lyclist = getLycList();
                    lycList.setListData(lyclist.toArray());
                    musicList.setBorder(BorderFactory.createTitledBorder("译文列表"));
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                
            }
        }
        
    }
    
    //读取txt文件内容
    private String getTxtContent(String filePath) throws Exception{
        
        if(filePath != null && filePath.contains(".txt")){
            File selFile= new File(filePath);
            BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(selFile),"gbk"));
            String line;
            String s = "";
            while((line=reader.readLine())!=null){
                s +=line+"\n";
            }
            return s;
        }else{
            return null;
        }
    }
    
    
    //打开文件选择器,选择MP3文件
    private class openButtonActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            
            File file = null;
            String fileName = "";
            int value = chooser.showOpenDialog(chooser);// 接受文件选择器的状态
            if (value == chooser.APPROVE_OPTION) {
                file = chooser.getSelectedFile();// 返回选中文件
                fileName = file.getName();
                mp3FilePath = file.getPath();
               // System.out.println("选中的文件名:"+fileName);
               // System.out.println("选中文件路径:"+mp3FilePath);
                Song s = new Song();
                s.setDir(mp3FilePath);
                s.setName(fileName);
                s.setId(fileName);
                s.setArtist_name(fileName);
                FileManager.addLog(s);
                stringlist = getMusicList();
                musicList.setListData(stringlist.toArray());
                musicList.setBorder(BorderFactory.createTitledBorder("本地歌曲列表   共"
                        + stringlist.size() + "首"));
                player = new PlayTest(s.getDir());
                    mp3Length = player.Length();
                    js.setMaximum(player.Length() * 1000);
                    jTextArea2.setText(String.format("%02d:%02d", player.Length() / 60,
                            player.Length() % 60));
                    sliderAction();
                    player.start(0);
                    player.state=1;
                if(pausingFlag!=null && pausingFlag.size()>1){
                    pausingFlag.clear();
                    pausingFlag.add("00:00:00");
                    stopTime = 0;
                }
                if(stopeTimeOfLentth != null && stopeTimeOfLentth.size()>0){
                    stopeTimeOfLentth.clear();
                }
            }  

        }
    }

    
    //播放按钮事件监听
    private class playButtonActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            //获取当前播放的时间并保存?
            //System.out.println("playButtonActionListener输出stopTime:"+stopTime);
            playmusic(stopTime / 25, true);
        }
    }
    
    
    //音乐播放
    private void playmusic(int t, boolean bool) {
        if (player != null) {
            if (bool)
            player.state = 0;
            player.stop();
        }
        
        try {
            Thread.sleep(500);
            } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            
        try {
                Song so = songlist.get(musicList.getSelectedIndex());
                mp3FilePath = so.getDir();
                player = new PlayTest(so.getDir());
                player = new PlayTest(mp3FilePath);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                player = new PlayTest(mp3FilePath);
            }
        if (bool) {
            mp3Length = player.Length();
            js.setMaximum(player.Length() * 1000);
            jTextArea2.setText(String.format("%02d:%02d", player.Length() / 60,
                    player.Length() % 60));
            sliderAction();
        }
        player.start(t);
    }
    
  //音乐回放
    private void replayMusic(int t,boolean bool) {
        if (player != null) {
            if (bool)
            player.state = 0;
            player.stop();
        }
        
        try {
            Thread.sleep(500);
            } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            
        try {
                Song so = songlist.get(musicList.getSelectedIndex());
                mp3FilePath = so.getDir();
                player = new PlayTest(so.getDir());
                player = new PlayTest(mp3FilePath);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                player = new PlayTest(mp3FilePath);
            }
        
        player.start(t);
    }
    
    
    //进度条跳转到当前暂停的时间
    private void sliderAction() {
        player.state = 1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                
                begintime = System.currentTimeMillis()-js.getValue();
                
                //System.out.println("sliderAction beginTime:"+begintime);
                
                while (player.state != 0 && stopTime == 0) {
                    //获取当前进度条时间
                    int s = js.getValue() / 1000;
                    
                        jTextArea1.setText(String.format("%02d:%02d", s / 60,s % 60));
                    
                    if (player.state == 1) {
                        long nowtime = System.currentTimeMillis();
                        
                        //当前时间减去播放时间=当前进度条时间
                        time = (int) (nowtime - begintime);
                        
                        js.setValue(time);
                        
                    } else {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        continue;
                    }
                    js.setValue(time);
                    jTextArea1.setText(String.format("%02d:%02d", (time/1000)/60,(time/1000)%60)); //当前播放时间
                    jTextArea2.setText(String.format("%02d:%02d", player.Length() / 60,
                                 player.Length() % 60)); //音频时长
                }
                while (player.state != 0 && stopTime != 0) {
                    //获取当前进度条时间
                    int s = (js.getValue()+stopTime/1000) / 1000;
                    
                        jTextArea1.setText(String.format("%02d:%02d", s / 60,s % 60));
                    
                    if (player.state == 1) {
                        long nowtime = System.currentTimeMillis();
                        time = (int) (nowtime - begintime);
                        js.setValue(time);
                        
                    } else {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        continue;
                    }
                    js.setValue(time);
                    jTextArea1.setText(String.format("%02d:%02d", (time/1000)/60,(time/1000)%60)); //当前播放时间
                    jTextArea2.setText(String.format("%02d:%02d", player.Length() / 60,
                                 player.Length() % 60)); //音频时长
                }
                while (player.state == 0 && stopTime != 0) {
                    //获取当前进度条时间
                    int s = (js.getValue()+stopTime/1000) / 1000;
                    
                        jTextArea1.setText(String.format("%02d:%02d", s / 60,s % 60));
                    
                    if (player.state == 1) {
                        long nowtime = System.currentTimeMillis();
                        time = (int) (nowtime - begintime);
                        js.setValue(time);
                        
                    } else {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        continue;
                    }
                    js.setValue(time);
                    jTextArea1.setText(String.format("%02d:%02d", (time/1000)/60,(time/1000)%60)); //当前播放时间
                    jTextArea2.setText(String.format("%02d:%02d", player.Length() / 60,
                                 player.Length() % 60)); //音频时长
                }
                
            }
        }).start();
    }

    
    //stop 按钮事件监听
    private class stopButtonActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(player.state==0){
                playmusic(stopTime / 25, true);
            }else
            if(player.state==1){
            player.state = 0;
            player.stop();
            /*
             * 暂停后恢复播放但是进度条的时间没有改变导致下一次暂停时获取错误的进度条时间信息
             */
            //获取当前进度条时间
            stopTime = js.getValue();
            int s = stopTime/1000;
            //获取当前时间
            
            pausingFlag.add(String.format("%02d:%02d:%02d.%03d", s/3600,s/60,s%60,stopTime%1000));
            //System.out.println(String.format("%02d:%02d:%03d", s/60,s%60,stopTime%1000));
            stopTimeOfNum.add(stopTime/1000);
            if(stopeTimeOfLentth.size()==0){
                stopeTimeOfLentth.add(stopTime/1000);
            }else 
            {
                stopeTimeOfLentth.add((stopTime/1000)-(stopeTimeOfLentth.get(stopeTimeOfLentth.size()-1)));
                
            }
            //System.out.println(stopeTimeOfNum.get(stopeTimeOfNum.size()-1));
            
           if(lineContent!=null&&lineContent.length!=0){
              lineContent[stopeTimeOfLentth.size()] =pausingFlag.get(stopeTimeOfLentth.size())+"--->"+ lineContent[stopeTimeOfLentth.size()];
              content = "";
              for (int i = 0; i < lineContent.length; i++) {
                  content += lineContent[i]+"\n";
              }
              textArea.setText("");
              textArea.append(content);
              lyclist = getLycList();
              lycList.setListData(lyclist.toArray());
              lycList.setBorder(BorderFactory.createTitledBorder("译文列表"));
           }
        }
        }
    }
    
    
    //clean 按钮事件监听 清空歌曲列表
    private class cleanButtonActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            //System.out.println("clean");
            FileManager.deleteLog();
            stringlist = getMusicList();
            musicList.setListData(stringlist.toArray());
            musicList.setBorder(BorderFactory.createTitledBorder("本地歌曲列表   共"
                    + stringlist.size() + "首"));
            textArea.setText("");
            js.setValue(0);
            jTextArea1.setText("00:00"); //当前播放时间
            jTextArea2.setText("00:00"); //音频时长
            openButton.setEnabled(false); //MP3按钮不可点击
            outPutPath.setText(""); 
            lyclist.clear();
            lycList.setListData(lyclist.toArray());
            lycList.setBorder(BorderFactory.createTitledBorder("译文列表"));
           }
           
    }
    
    
    //cutButton 事件监听
    private class cutButtonActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            
            for (int i = 0; i < pausingFlag.size(); i++) {
                //System.out.println(pausingFlag.size());
                //System.out.println(stopeTimeOfNum.size());
                //System.out.println("mpeFilePath:"+mp3FilePath);
                //System.out.println("mpeFilePath:"+mp3FilePath.substring(0, mp3FilePath.lastIndexOf("\\")));
                
                File file = new File(mp3FilePath.substring(0, mp3FilePath.lastIndexOf("\\"))+"\\mp3\\"+(i+1)+".mp3");
                
                
                //获取父目录
                File fileParent = file.getParentFile();
                //判断是否存在
                if (!fileParent.exists()) {
                //创建父目录文件
                fileParent.mkdirs();
                }
                if(file.exists()){
                    file.delete();
                    System.out.println("已存在的文件被删除了!");
                }
                try {
                    System.out.println("stopTime:"+pausingFlag.get(i));
                    //System.out.println("stopTimeOfNum:"+stopeTimeOfNum.get(i));
                    //System.out.println(mp3FilePath);
                    //System.out.println(file.getPath());
                    if(i<stopeTimeOfLentth.size()){
                        FFMpegUtil.mp3Convetor(mp3FilePath , pausingFlag.get(i) , String.valueOf(stopeTimeOfLentth.get(i)), file.getPath());
                    }else{
                        FFMpegUtil.mp3Convetor(mp3FilePath , pausingFlag.get(i) , String.valueOf(mp3Length-stopTime/1000), file.getPath());
                    }
                   
                    //System.out.println(file.getPath());
                    //System.out.println("切割MP3成功!");
                    outPutPath.setText("输出文件路径:"+file.getPath());
                    
                    File txt = new File(mp3FilePath.substring(0, mp3FilePath.lastIndexOf("\\"))+"\\book.txt");
                    FileOutputStream fos = new FileOutputStream(txt);
                    PrintWriter pw = new PrintWriter(fos);
                    File info = new File(mp3FilePath.substring(0, mp3FilePath.lastIndexOf("\\"))+"\\bookTime.txt");
                    FileOutputStream infoFos = new FileOutputStream(info);
                    PrintWriter infoPw = new PrintWriter(infoFos);
                    String []ss = new String[lineContent.length];
                    String s ="";
                    String timeInfo="";
                    for (int j = 0; j < lineContent.length; j++) {
                        if(lineContent[j].contains("--->")){
                         ss[j] =lineContent[j].replace(lineContent[j].substring(0, 16), "###### ");
                         timeInfo += lineContent[j].substring(0, 12)+System.getProperty("line.separator");
                        }else{
                            ss[j] = "###### "+lineContent[j];
                        }
                        s += ss[j]+System.getProperty("line.separator");
                    }
                    pw.write(s);
                    infoPw.write(timeInfo);
                    pw.flush();
                    infoPw.flush();
                    if(pw!=null)
                        pw.close();
                    if(infoPw!=null)
                        infoPw.close();
                    if(fos!=null)
                        fos.close();
                    if(infoFos!=null)
                        infoFos.close();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }
    
    
    private class myPanel extends JPanel {
        ImageIcon icon;
        Image img;

        public myPanel() {
            // /img/HomeImg.jpg 是存放在你正在编写的项目的bin文件夹下的img文件夹下的一个图片
            icon = new ImageIcon("pic\\bg.jpg");
            img = icon.getImage();
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            // 下面这行是为了背景图片可以跟随窗口自行调整大小,可以自己设置成固定大小
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
        }

    }
}
package player;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.security.spec.ECPrivateKeySpec;

import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;

import javazoom.jl.player.PlayerApplet;
import javazoom.jl.player.advanced.*;
import javazoom.jl.converter.Converter;
import javazoom.jl.decoder.*;
import javazoom.jl.player.*;

public class PlayTest implements Runnable{
    Thread t;
    public int state; //0不处于播放状态;1正在播放;-1 记时器暂停 不影响播放
    private int length;
    public int start;
    private String dir;
    BufferedInputStream buffer;
    private AdvancedPlayer player;
    public PlayTest(String dir){   //创建MP3Play的对象,并传入歌曲本地路径
        this.dir = dir;
        getLength();
        
		try {
			buffer = new BufferedInputStream(new FileInputStream(dir));
			player = new AdvancedPlayer(buffer);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    public void setDir(String dir){
        this.dir = dir;        
    }
    public int Length() {
		return length;
	}
    private void play(){     //调用play()方法就可以播放了
        try{
        	player = new AdvancedPlayer(buffer);
//            state = true;
        	pbListener();
            player.play(start, length*1000);
        }catch (Exception e) {
            System.out.println(e);
        }
    }
    public void stop(){     //调用stop()方法可以让歌曲停止播放
        player.close();
    }
    public void pbListener() {
    	PlaybackListener pbl = new TestPlaybackListener();
    	player.setPlayBackListener(pbl);
	}
//    public int getLarge(){
//    	
//        return player.();
//    }
    private class TestPlaybackListener extends PlaybackListener {
		@Override
		public void playbackFinished(PlaybackEvent e) {
			// TODO Auto-generated method stub
			super.playbackFinished(e);
			state = 0;
		}
		@Override
		public void playbackStarted(PlaybackEvent e) {
			// TODO Auto-generated method stub
			super.playbackStarted(e);
		}
	}
    @Override
    public void run(){      //用线程启动play(),这样才能正常使用stop()
        play();
    }
    
    public Thread start(int st){
    	start = st;
    	
    	if (state == -1) 
    	    stop();
        t = new Thread(this);
        t.start();
        return t;
    }
    private void getLength() {
    	File file = new File(dir);  
        try {  

            MP3File f = (MP3File)AudioFileIO.read(file);  

            MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();  

            length = audioHeader.getTrackLength();     

        } catch(Exception e) {  
            
            e.printStackTrace();  
            
        }  
	}


}

这里是主要的代码片段

要实现小程序音频播放器播放编辑好的内容,你需要完成以下步骤: 1. 编辑音频文件:使用专业的音频编辑软件,如Adobe Audition,将音频文件剪辑、混音、调整音量等,制作出符合要求的音频文件。 2. 将音频文件上传到服务器:将编辑好的音频文件上传到服务器,确保用户可以通过小程序访问该文件。 3. 使用小程序的音频组件:在小程序中使用音频组件,将音频文件的URL传递给组件,使其可以播放该文件。 以下是一个简单的代码示例: ```xml <audio src="{{audioUrl}}" id="myAudio" /> <button bindtap="playAudio">播放</button> <button bindtap="pauseAudio">暂停</button> ``` ```javascript Page({ data: { audioUrl: 'https://example.com/audio.mp3', myAudio: null }, onReady: function () { this.setData({ myAudio: wx.createInnerAudioContext() }) }, playAudio: function () { this.data.myAudio.src = this.data.audioUrl this.data.myAudio.play() }, pauseAudio: function () { this.data.myAudio.pause() } }) ``` 在这个示例中,我们首先定义了一个音频组件和两个按钮,分别用于播放和暂停音频。然后,在页面加载完成时,我们创建了一个音频上下文对象,并将其保存在data中。最后,我们在播放和暂停按钮的事件处理程序中,分别设置音频URL并播放或暂停音频。 需要注意的是,为了保证音频播放效果的流畅性,应尽量使用较小的音频文件,并确保服务器的稳定性和响应速度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值