0

I'm working on a project that constantly changes pages and repaints the page and i need a mute and unmute to have music playing in the background. My problem is whenever it changes pages and repaints and stuff the music resets and stops. I'm making it so whenever the mouse is pressed on the mute/unmute button then the music will either play or stop depending on if it is muted or not.

Anyone have any simple coding i could use that will create a mute/unmute button to play music in the background that won't be interrupted every time the page changes?

I am making this on java on eclipse on an Applet.

Please dumb it down a bit for me because i'm kind of new to java so i don't know too much. Thanks.

Here is some code where the page changes:

public void paint(Graphics g){   
    switch (roomPage){
    case 0: homeScreen(g); break;
    case 1: instructionsPage(g); break;
    case 2: startPage(g); break;
    }
}

and here is some code on what i want to happen:

public void mousePressed(MouseEvent me) {
    if (xPos > 0 && xPos < 0+64 && yPos >0 &&  
            yPos < 0+64){
        if(soundMuted == false){
         //since it's not muted and it is clicked then the music will change
         //to "soundMuted = true" and the music will stop
         soundMuted = true;
        }
        else {
        //since it will be changing to "soundMuted = false" the music will
        //start again
        soundMuted = false;
        }
    }
}

The problem with ^ this though is that whenever i use it and it goes to a different page it for some reason resets it back to it's default state which is false. I just want an example to simplify a mute/unmute button that can play uninterrupted in the background unless the button is clicked.

Intrinza
  • 35
  • 2
  • 8
  • Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer May 28 '15 at 00:03
  • @MadProgrammer There i tried to give somewhat of an example. – Intrinza May 28 '15 at 00:13
  • So, how are you playing the music? Can't really dump you "example" code in an IDE and run it :P – MadProgrammer May 28 '15 at 00:30
  • @MadProgrammer I deleted it :/ but i was using something with a clip and using .start(); to make it play and .stop(); to make it stop playing.. do you know an easier way? i just need a simple way of making it play and mute uninterruptedly. – Intrinza May 28 '15 at 00:46
  • Which `Clip`? `java.applet.AudioClip` or `javax.sound.sampled.Clip`? – MadProgrammer May 28 '15 at 00:48
  • [Audio volume control (increase or decrease) in Java](http://stackoverflow.com/questions/953598/audio-volume-control-increase-or-decrease-in-java) – MadProgrammer May 28 '15 at 00:49
  • @MadProgrammer i'm pretty sure i was using java.applet.AudioClip ... & how would use ^ to not be interrupted every time the page changes? – Intrinza May 28 '15 at 00:57
  • Well, [this](http://stackoverflow.com/questions/30449573/simple-java-how-to-use-isrunning-on-an-audio-clip/30449827#30449827) uses an applet and `javax.sound.sampled.Clip`. *"i just need a simple way of making it play and mute uninterruptedly"* would suggest that you want to turn the volume off, or do you want to pause the play back? – MadProgrammer May 28 '15 at 00:59
  • `javax.sound.sampled.Clip` has `getFramePosition` and `setFramePosition` which could be used to act as a "pause" function - [for example](http://stackoverflow.com/questions/24274997/java-wav-player-adding-pause-and-continue) – MadProgrammer May 28 '15 at 01:02
  • @MadProgrammer I can't figure out how to use that code you gave me and make it so when mouseispressed it will either play or mute – Intrinza May 28 '15 at 02:28
  • So, "mute" means, "continue playing, but with the volume turned down"? – MadProgrammer May 28 '15 at 02:31
  • @MadProgrammer No sorry, by mute i meant pause the music. – Intrinza May 28 '15 at 02:35

1 Answers1

0

So, based on this example

I wrapped the pause/resume functionality it separate methods.

You will need to paste the path to an audio file in the JTextField and press load, then you can press the "Click me to play" label to start playing and "Click me to pause" to pause it.

(Before anybody jumps all over me for not using buttons, the OP is using a MouseListener, so I'm "trying" to mimic what little of their work flow I can see)

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
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.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class SimplyPlayer {

    public static void main(String[] args) {
        new SimplyPlayer();
    }

    public SimplyPlayer() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Clip clip;
        private JTextField audioFile;
        private int lastFrame;

        public TestPane() {
            setLayout(new BorderLayout());

            ActionListener loadAction = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (clip != null) {
                        clip.stop();
                        clip.close();
                    }

                    try {
                        loadClip(new File(audioFile.getText()));
                        System.out.println("loaded");
                    } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
                        ex.printStackTrace();
                    }
                }
            };

            audioFile = new JTextField(20);
            audioFile.addActionListener(loadAction);

            JButton load = new JButton("Load");
            load.addActionListener(loadAction);

            JPanel loadPanel = new JPanel(new BorderLayout());
            loadPanel.add(audioFile);
            loadPanel.add(load, BorderLayout.EAST);

            add(loadPanel, BorderLayout.NORTH);

            JPanel panel = new JPanel(new GridBagLayout());

            JLabel play = new JLabel("Click me to play");
            JLabel pause = new JLabel("Click me to pause");

            play.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(50, 50, 50, 50)));
            pause.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(50, 50, 50, 50)));

            panel.add(play);
            panel.add(pause);

            add(panel);

            MouseListener handler = new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getSource() == play) {
                        resume();
                    } else if (e.getSource() == pause) {
                        pause();
                    }
                }

            };

            play.addMouseListener(handler);
            pause.addMouseListener(handler);

        }

        protected void loadClip(File audioFile) throws LineUnavailableException, IOException, UnsupportedAudioFileException {

            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            this.clip = (Clip) AudioSystem.getLine(info);
            this.clip.open(audioStream);

        }

        public void pause() {

            if (clip != null && clip.isRunning()) {
                lastFrame = clip.getFramePosition();
                System.out.println("Stop");
                clip.stop();
            }

        }

        public void resume() {

            if (clip != null && !clip.isRunning()) {
                // Make sure we haven't passed the end of the file...
                if (lastFrame < clip.getFrameLength()) {
                    clip.setFramePosition(lastFrame);
                } else {
                    clip.setFramePosition(0);
                }
                System.out.println("Start");
                clip.start();
            }

        }
    }

}

Loading a audio file within an applet is a little more complicated, but is demonstrated here

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • So using that ^ what you just made how would i make it so instead of using the load button and typing in the path.. i can just put the path in the code and it will automatically load the song instead of having to type out the path every time? – Intrinza May 28 '15 at 03:28
  • *"Loading a audio file within an applet is a little more complicated, but is demonstrated [here](http://stackoverflow.com/questions/30449573/simple-java-how-to-use-isrunning-on-an-audio-clip/30449827#30449827)"* – MadProgrammer May 28 '15 at 03:29
  • I meant using that was you just made. Not in an applet.. how would i just make the song automatically load onto it? – Intrinza May 28 '15 at 03:33
  • Yes, and the link I just gave uses an `JApplet` to load an embedded resource. When you do that is up to you, just make sure that the `pause` and `resume` methods can access the `Clip` as demonstrated above. You know have three runnabled examples of how this could be done, two showing how to pause/resume a clip and one which shows how you might load it...Since you've only provided me out of context clips of code, I have no real idea of how it would be incorporated into your code. – MadProgrammer May 28 '15 at 03:38