HỎI Cho em hỏi về cách tạo button mute/unmute trong java ạ

cetee

New Member
5/1/21
5
0
1
tp hcm
Hiện em đang làm đồ án về 1 game, em muốn hỏi cách tạo button mute/unmute ? Nhờ mọi người hướng dẫn hoặc cho em code ví dụ được không ạ? Em cảm ơn rất nhiều ạ.
 

Joe

Thành viên VIP
21/1/13
2,997
1,320
113
Are you asking for JAVA Android or for JAVA? Without codes (which give me the precise picture about your problem) I give yo the same opaque answer:
- JAVA: see the example HERE
Java:
import java.awt.*;
import javax.swing.*;
import javax.sound.sampled.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SoundMixer {

    public Component getGui() {
        JPanel gui = new JPanel(new GridLayout(0,1));

        Mixer.Info[] mixers = AudioSystem.getMixerInfo();
        System.out.println(
                "There are " + mixers.length + " mixer info objects");
        for (Mixer.Info mixerInfo : mixers) {
            System.out.println("mixer name: " + mixerInfo.getName());
            Mixer mixer = AudioSystem.getMixer(mixerInfo);
            Line.Info[] lineInfos = mixer.getSourceLineInfo();
            for (Line.Info lineInfo : lineInfos) {
                System.out.println("  Line.Info: " + lineInfo);
                try {
                    Line line = mixer.getLine(lineInfo);
                    FloatControl volCtrl = (FloatControl)line.getControl(
                            FloatControl.Type.MASTER_GAIN);
                    VolumeSlider vs = new VolumeSlider(volCtrl);
                    gui.add( new JLabel(volCtrl.toString()) );
                    gui.add( vs.getVolume() );
                    System.out.println(
                            "    volCtrl.getValue() = " + volCtrl.getValue());
                } catch (LineUnavailableException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException iaEx) {
                    System.out.println("    " + iaEx);
                }
            }
        }

        return gui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                SoundMixer sm = new SoundMixer();
                Component c = sm.getGui();
                JOptionPane.showMessageDialog(null, c);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}

class VolumeSlider {

    JSlider volume;

    VolumeSlider(final FloatControl volumeControl) {
        volume = new JSlider(
                (int) volumeControl.getMinimum() * 100,
                (int) volumeControl.getMaximum() * 100,
                (int) volumeControl.getValue() * 100);
        ChangeListener listener = new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                float val = volume.getValue() / 100f;
                volumeControl.setValue(val);
                System.out.println(
                        "Setting volume of " + volumeControl.toString() + 
                        " to " + val);
            }
        };
        volume.addChangeListener(listener);
    }

    public JSlider getVolume() {
        return volume;
    }
}
- JAVA Android
Java:
AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(true);
 

cetee

New Member
5/1/21
5
0
1
tp hcm
1609859738101.pngthe interface looks like this, I have been learning java for a few week, now i would like to create a button mute / unmute, if you can view the code and fix it, i will grateful to you so much, Thank you
 

Joe

Thành viên VIP
21/1/13
2,997
1,320
113
@cetee
sorry. drive.google.com checks for virus and thinks that your "rar" package contains some Covid-19 and breaks the download process :(
Read THIS and try to follow the procedure...;)
 

cetee

New Member
5/1/21
5
0
1
tp hcm
Thank you :((

Java:
package menuBarGame;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;

public class Game extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    private int point;
    private int question_num = 0;

    // Swing components
    private Container container;
    private JPanel questionPane, answerPane, nextChallengePane, mutePane;
    private static JPanel FilePane;
    private JTextField answer;
    private JLabel checker, question, score;
    
    private JButton mute;
    
    private BufferedReader reader_Ans;
    private BufferedReader reader_Ques;
    private File questionFile, answerFile;
    private JMenuBar menuBar;
    final JFileChooser fileDialog = new JFileChooser();
    static ArrayList<String> ques = new ArrayList<String>();
    static ArrayList<String> ans = new ArrayList<String>();
    // Queue and Stack
    private Queue<File> queue = new LinkedList<> ();
    private Stack<File> stack = new Stack<File> ();
    private int isStack;
    public Object synth;

    public Game() throws IOException {
        super("Challenge Gameshow"); // use this instead of setTitle for JFrame
        init();
        try {
            Music music = new Music();
        } 
        catch (LineUnavailableException e) {} 
        catch (IOException e) {} 
        catch (UnsupportedAudioFileException e) {}
        
       
    }

    private void init() throws IOException {
        // readFile(); // add this line to fix bug

        this.point = 0;
        container = getContentPane();
        container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); // arrange vertialy

        renderFileChooser();
        // container.add(FilePane);
        
        renderQuestionPane();
        renderAnswerPane();
        renderNextChallengePane();
        renderMutePane();
        container.add(questionPane);
        container.add(answerPane);
        container.add(nextChallengePane);
        container.add(mutePane);

        menuBar = new Menu(FilePane);

        this.setJMenuBar(menuBar);
        renderWindow();
    }

    /**
     * Add this funciton to fix bug
     * 
     * @throws IOException
     */
    private void readFile() throws IOException {
        String question_name = questionFile.getName();
        
        answerFile = new File(questionFile.getParentFile().getAbsolutePath() + "\\" + question_name.substring(0, question_name.lastIndexOf("_")) + "_answer.txt");
        System.out.println(questionFile.getParentFile().getAbsolutePath() + "\\" + question_name.substring(0, question_name.lastIndexOf("_")) + "_answer.txt");
        InputStream inputStream_Ques = new FileInputStream(questionFile);
        
        InputStream inputStream_Ans = new FileInputStream(answerFile);
        InputStreamReader inputStreamReader_Ques = new InputStreamReader(inputStream_Ques);
        InputStreamReader inputStreamReader_Ans = new InputStreamReader(inputStream_Ans);
        
        reader_Ques = new BufferedReader(inputStreamReader_Ques);
        reader_Ans = new BufferedReader(inputStreamReader_Ans);

        // clear list
        ques.clear();
        ans.clear();
        String line_Ques = "";
        String line_Ans = "";
        while ((line_Ques = reader_Ques.readLine()) != null && (line_Ans = reader_Ans.readLine()) != null) {
            ques.add(line_Ques);
            ans.add(line_Ans);
        }

        // close stream
        inputStream_Ques.close();
        inputStreamReader_Ans.close();
    }

    private void renderWindow() {
        setSize(400, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
    }

    private void renderFileChooser() {
        FilePane = new JPanel();
        FilePane.setPreferredSize(new Dimension(400, 100));

        // question
        JPanel questionFilePane = new JPanel(new FlowLayout(1, 10, 0));
        JButton ques_choose_file = new JButton("Choose File");
        JLabel ques_file_choosed = new JLabel("");

        // JFileChooser config
        fileDialog.setDialogTitle("File");
        fileDialog.setCurrentDirectory(new java.io.File(".")); // get current directory
        fileDialog.setMultiSelectionEnabled(true);

        ques_choose_file.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                int res = fileDialog.showOpenDialog(null);
                if (res == JFileChooser.APPROVE_OPTION) {
                    String[] options = {"Queue", "Stack"};
                     isStack = JOptionPane.showOptionDialog(null, "Choose play type",
                             "Select play type",
                             JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
                     File[] files = fileDialog.getSelectedFiles();
                    for (File file : files) { 
                        if (isStack == 0) { // Means choose queue
                            queue.add(file);
                        } else if (isStack == 1) { // Means choose stack
                            stack.add(file);
                        }    
                    }}
            }

        });

        questionFilePane.add(new JLabel("File: "));
        questionFilePane.add(ques_choose_file);
        questionFilePane.add(ques_file_choosed);

        // Confirm button
        JButton confirmBtn = new JButton("Let's go");
        confirmBtn.setPreferredSize(new Dimension(160, 30));
        confirmBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // read file
                    if (isStack == 0) { // Means choose Queue    
                        handleQueue();
                    } else if (isStack == 1) { // Means choose Stack
                        handleStack();
                    }
                    makeNewGame();
                } catch (Exception ecep) {
                    JOptionPane.showMessageDialog(container, "Cannot Open file", "Error", JOptionPane.CANCEL_OPTION);
                }
            }
        });

        FilePane.add(questionFilePane);
        
        FilePane.add(confirmBtn);
    }
    
    private void handleQueue() throws IOException {
        questionFile = queue.remove();
        readFile();
    }
    private void handleStack() throws IOException {
        questionFile = stack.pop();
        readFile();
    }
    private void makeNewGame() {
        // config new game
        question_num = 0;
        point = 0;
        question.setText("Quesiton: " + ques.get(question_num));
        score.setText("Total: " + point);
        answer.setEnabled(true);
    }

    
    private void renderQuestionPane() {
        questionPane = new JPanel(new FlowLayout(1, 10, 10));

        question = new JLabel("Quesiton: ");

        questionPane.add(question);
    }

    private void renderAnswerPane() {
        answerPane = new JPanel(new FlowLayout(1, 5, 5));

        answer = new JTextField(20);
        answer.addActionListener(this); // add event listener
        checker = new JLabel("");
        score = new JLabel("Total: " + this.point);

        answer.setEnabled(false);

        answerPane.add(new JLabel("Your answer: "));
        answerPane.add(answer);
        answerPane.add(score);
        answerPane.add(checker);
    }
    
    private void renderNextChallengePane() {
        nextChallengePane = new JPanel();
        JButton next = new JButton("NEXT");
        next.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // read file
                    if (isStack == 0) { // Means choose Queue    
                        handleQueue();
                    } else if (isStack == 1) { // Means choose Stack
                        handleStack();
                    }
                    makeNewGame();
                } catch (Exception ecep) {
                    JOptionPane.showMessageDialog(container, "Cannot Open file", "Error", JOptionPane.CANCEL_OPTION);
                }
            }
        });
        
        nextChallengePane.add(next);
    }
    
    private void renderMutePane() {
        mutePane = new JPanel();
        JButton mute = new JButton("MUTE");
        mute.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if (isStack == 0) { // Means choose Queue    
                        handleQueue();
                    } else if (isStack == 1) { // Means choose Stack
                        handleStack();
                    }
                    makeNewGame();
                } catch (Exception ecep) {
                    JOptionPane.showMessageDialog(container, "Cannot Open file", "Error", JOptionPane.CANCEL_OPTION);

                }
            }
        });
        mutePane.add(mute);

    }



    /*public Game() throws IOException {
        super("Challenge Gameshow"); // use this instead of setTitle for JFrame
        init();
        try {
            Music music = new Music();
        } 
        catch (LineUnavailableException e) {} 
        catch (IOException e) {} 
        catch (UnsupportedAudioFileException e) {}
        
       
    }*/
    
    
    public static void main(String[] args) throws IOException {
        Game g = new Game();
        
    }

    // Catch event
    @Override
    public void actionPerformed(ActionEvent e) {
        String res = answer.getText();

        if (res.equalsIgnoreCase(ans.get(question_num))) {
            try
            {
                WinMusic wnMusic = new WinMusic();
                wnMusic.start();
            }
            catch (LineUnavailableException e1) {}
            catch (IOException e1) {} 
            catch (UnsupportedAudioFileException e1) {} 
            question_num++;
            point++;
            checker.setText("");
            answer.setText("");
            score.setText("Score: " + point);

            // try and catch error when out of quesion ==> end game
            try {
                   question.setText("Question: " + ques.get(question_num));
            } 
            catch (IndexOutOfBoundsException exception) {
                question.setText("You win!!!");
                answer.setEnabled(false); // disable answer when game end
            }
        } else 
        {
            checker.setText("Wrong aswer!!!");
            try
            {
                LoseMusic wnMusic = new LoseMusic();
                wnMusic.start();
            }
            catch (LineUnavailableException e1) {}
            catch (IOException e1) {} 
            catch (UnsupportedAudioFileException e1) {} 
        }
    }

    public void close() {
        // TODO Auto-generated method stub
        
    }

}
 
Sửa lần cuối:

Joe

Thành viên VIP
21/1/13
2,997
1,320
113
You forgot to upload the Music.java so that I cannot recompile and reproduce the problem you've encountered. But so far I could see that you have problems with the readFile() method. And I have no idea what you want to do with the ArrayList after loading it. The Mute button just does that. Questions:
What do you want to do with the Mute button?
- stop the music?
- silence it slowly?
 
  • Love
Reactions: cetee

cetee

New Member
5/1/21
5
0
1
tp hcm
I want to silence the sound while the music still plays :(( because I don't know how to make it work so I just create the Mute button without any function, so sorry because my English is not good, I hope you can understand my mean :(( thank you so much

PHP:
package menuBarGame;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Music
{
    public Music() throws LineUnavailableException, IOException, UnsupportedAudioFileException
    {

       
        File file = new File("C:\\Users\\Admin\\Downloads\\asd\\menuBarGame\\POL-going-upscale-short.wav");
        AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
        Clip clip = AudioSystem.getClip();
        clip.open(audioStream);
        clip.start();
        clip.loop(10);

    }
}
 

Joe

Thành viên VIP
21/1/13
2,997
1,320
113
Your codes contains too many errors. example
Java:
// wrong:
menuBar = new Menu(FilePane);
// correct
menuBar = new JMenuBar();
and some missing pieces such as WinMusic and LoseMusic so that I have to convert them to Music. Next time you should give the readers who want to help you the minimum codes that work. NOT that one has to work-around your codes.

Back to the Mute: Clip allows you to get the controller and with it you can mute as silent as you want: either with a JSlider (as I do) or with the simple JOptionPane.
The modifications
Music.java
Java:
import java.io.*;
import java.util.*;
import javax.sound.sampled.*;
public class Music
{
    public Music() throws LineUnavailableException, IOException, UnsupportedAudioFileException
    {
        File file = new File("music1.wav");
        AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
        clip = AudioSystem.getClip();
        clip.open(audioStream);
        control = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
        max = control.getMaximum();
        min = control.getMinimum();
    }
    public float getMaxVolume() {
      return max;
    }
    public float getMinVolume() {
      return min;
    }
    public void setLevel(float vol) {
      if (vol > max) vol = max;
      else if (vol < min) vol = min;
      control.setValue(vol);
    }
    public void start() {
        clip.start();
        clip.loop(10);
    }
    private Clip clip;
    private float max, min;
    private FloatControl control;
}
and the modification for the MUTE JSlider
Java:
    public Game() throws IOException {
        super("Challenge Gameshow"); // use this instead of setTitle for JFrame
        init();
        try {
            music = new Music(); // <------- make it global
            music.start();
            // set scaling MUTE JSlider
            slider.setMaximum(100);
            slider.setMinimum(0);
            slider.setValue(0);
            slider.setMajorTickSpacing(10);
            slider.setMinorTickSpacing(5);
            slider.setPaintTicks(true);
            slider.setPaintLabels(true);

        }
        catch (LineUnavailableException e) {}
        catch (IOException e) {}
        catch (UnsupportedAudioFileException e) {}


    }
    ....

    private void renderMutePane() {
        mutePane = new JPanel( );
        // create JSlider for MUTING the music
        slider = new JSlider(JSlider.HORIZONTAL);
        slider.addChangeListener(e -> {
           music.setLevel((float)(-0.2*((JSlider)e.getSource()).getValue()));
        });
        JLabel lab = new JLabel("MUTE");
        mutePane.add(lab);
        /*
        JButton mute = new JButton("MUTE");
        .....
        */
    }
   ...
gameMute.png
 
Sửa lần cuối: