io.github.jeremgamer.editor.panels.MusicFrame.java Source code

Java tutorial

Introduction

Here is the source code for io.github.jeremgamer.editor.panels.MusicFrame.java

Source

/**
 *   Copyright 2014/2015 JeremGamer
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. * 
 */

package io.github.jeremgamer.editor.panels;

import io.github.jeremgamer.editor.Editor;
import io.github.jeremgamer.editor.files.GeneralSave;
import io.github.jeremgamer.resources.images.ImageGetter;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.commons.io.IOUtils;

public class MusicFrame extends JDialog {

    /**
     * 
     */
    private static final long serialVersionUID = -3792253242497741136L;

    private JPanel content = new JPanel();
    private JToggleButton preview = new JToggleButton("Aperu");
    private JLabel name = new JLabel("");

    private JRadioButton one = new JRadioButton("Une fois");
    private JRadioButton loop = new JRadioButton("En boucle");
    private JSlider volume = new JSlider();

    private Clip clip;
    AudioInputStream audioStream;
    AudioFormat format;
    DataLine.Info info;
    private FloatControl gainControl;
    private double gain = 1.0D;
    private float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);

    public MusicFrame(JFrame frame, final GeneralSave gs) {

        ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>();
        try {
            icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png")));
            icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png")));
            icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png")));
            icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png")));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        this.setIconImages((List<? extends Image>) icons);

        this.setTitle("Musique");
        this.setSize(new Dimension(300, 225));

        this.addWindowListener(new WindowListener() {
            @Override
            public void windowActivated(WindowEvent event) {
            }

            @Override
            public void windowClosed(WindowEvent event) {
            }

            @Override
            public void windowClosing(WindowEvent event) {
                try {
                    gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (clip != null) {
                    clip.stop();
                    clip.close();
                    try {
                        audioStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void windowDeactivated(WindowEvent event) {
            }

            @Override
            public void windowDeiconified(WindowEvent event) {
            }

            @Override
            public void windowIconified(WindowEvent event) {
            }

            @Override
            public void windowOpened(WindowEvent event) {
            }
        });

        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

        this.setModal(true);
        this.setLocationRelativeTo(frame);

        JPanel properties = new JPanel();
        properties.setBorder(BorderFactory.createTitledBorder("Lecture"));
        ButtonGroup bg = new ButtonGroup();
        bg.add(one);
        bg.add(loop);
        one.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent event) {
                JRadioButton rb = (JRadioButton) event.getSource();
                if (rb.isSelected()) {
                    gs.set("music.reading", 0);
                    try {
                        gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (clip != null) {
                        if (clip.isRunning())
                            clip.loop(0);
                    }
                }
            }
        });
        loop.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent event) {
                JRadioButton rb = (JRadioButton) event.getSource();
                if (rb.isSelected()) {
                    gs.set("music.reading", 1);
                    try {
                        gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (clip != null) {
                        if (clip.isRunning())
                            clip.loop(Clip.LOOP_CONTINUOUSLY);
                    }
                }
            }
        });
        properties.add(one);
        properties.add(loop);
        if (gs.getInt("music.reading") == 0) {
            one.setSelected(true);
        } else {
            loop.setSelected(true);
        }

        volume.setMaximum(100);
        volume.setMinimum(0);
        volume.setValue(30);
        volume.setPaintTicks(true);
        volume.setPaintLabels(true);
        volume.setMinorTickSpacing(10);
        volume.setMajorTickSpacing(20);
        volume.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent event) {
                JSlider slider = (JSlider) event.getSource();
                double value = slider.getValue();
                gain = value / 100;
                dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
                if (clip != null)
                    gainControl.setValue(dB);
                gs.set("music.volume", (int) value);
            }
        });
        volume.setValue(gs.getInt("music.volume"));
        properties.add(volume);
        properties.setPreferredSize(new Dimension(300, 125));

        content.add(properties);

        JPanel browsePanel = new JPanel();
        browsePanel.setBorder(BorderFactory.createTitledBorder(""));
        JButton browse = new JButton("Parcourir...");
        if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
            preview.setEnabled(false);
            browse.setText("");
            try {
                browse.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        browse.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                JButton button = (JButton) event.getSource();
                if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
                    if (clip != null) {
                        clip.stop();
                        clip.close();
                        try {
                            audioStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    name.setText("");
                    preview.setEnabled(false);
                    button.setText("Parcourir...");
                    button.setIcon(null);
                    new File("projects/" + Editor.getProjectName() + "/music.wav").delete();
                    gs.set("music.name", "");
                } else {
                    String path = null;
                    JFileChooser chooser = new JFileChooser(Editor.lastPath);
                    FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio (WAV)", "wav");
                    chooser.setFileFilter(filter);
                    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    int option = chooser.showOpenDialog(null);
                    if (option == JFileChooser.APPROVE_OPTION) {
                        path = chooser.getSelectedFile().getAbsolutePath();
                        Editor.lastPath = chooser.getSelectedFile().getParent();
                        copyMusic(new File(path));
                        button.setText("");
                        try {
                            button.setIcon(
                                    new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        gs.set("music.name", new File(path).getName());
                        try {
                            gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        name.setText(new File(path).getName());
                        preview.setEnabled(true);
                    }
                }
            }

        });
        if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
            preview.setEnabled(true);
        } else {
            preview.setEnabled(false);
        }
        preview.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                JToggleButton tb = (JToggleButton) event.getSource();
                if (tb.isSelected()) {
                    try {
                        audioStream = AudioSystem.getAudioInputStream(
                                new File("projects/" + Editor.getProjectName() + "/music.wav"));
                        format = audioStream.getFormat();
                        info = new DataLine.Info(Clip.class, format);
                        clip = (Clip) AudioSystem.getLine(info);
                        clip.open(audioStream);
                        clip.start();
                        gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
                        gainControl.setValue(dB);
                        if (loop.isSelected()) {
                            clip.loop(Clip.LOOP_CONTINUOUSLY);
                        } else {
                            clip.loop(0);
                        }
                        clip.addLineListener(new LineListener() {
                            @Override
                            public void update(LineEvent event) {
                                Clip clip = (Clip) event.getSource();
                                if (!clip.isRunning()) {
                                    preview.setSelected(false);
                                    clip.stop();
                                    clip.close();
                                    try {
                                        audioStream.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                        });
                    } catch (Exception exc) {
                        exc.printStackTrace();
                    }
                } else {
                    clip.stop();
                    clip.close();
                    try {
                        audioStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        });
        JPanel buttons = new JPanel();
        buttons.setLayout(new BorderLayout());
        buttons.add(browse, BorderLayout.WEST);
        buttons.add(preview, BorderLayout.EAST);
        browsePanel.setLayout(new BorderLayout());
        browsePanel.add(buttons, BorderLayout.NORTH);
        browsePanel.add(name, BorderLayout.SOUTH);

        name.setPreferredSize(new Dimension(280, 25));
        name.setText(gs.getString("music.name"));
        content.add(browsePanel);

        this.setContentPane(content);
        this.setVisible(true);
    }

    private void copyMusic(File file) {
        try {
            FileOutputStream fos = new FileOutputStream(
                    new File("projects/" + Editor.getProjectName() + "/music.wav"));
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            IOUtils.copy(fis, fos);
            fos.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}