-2

I know how to play audio, the trouble is that the computer skips over the line. I watched a tutorial that said to use the .next() object in the Scanner class, to make the computer wait for user input, to stop the audio(a song) or replay it, but I want my user input to use a JTextField and JButton so how would I go about doing that?

I have 2 classes, the first class takes in the the input of the other(whether to play, pause, skip, stop), and does an action.

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

import javax.sound.sampled.*;

public class Main {
public static void main(String[] args) {

    new myFrame();

}

public static void playMusic( String response, String response2)  throws 
UnsupportedAudioFileException, IOException, LineUnavailableException  {

    Scanner scanner = new Scanner(System.in);

    File song1 = new File("Underground Academy - Hanu Dixit.wav");
    File song2 = new File("Body of Water - TrackTribe.wav");
    AudioInputStream audioStream = AudioSystem.getAudioInputStream(song1);
    Clip clip = AudioSystem.getClip();

    long position = 0;

    int pause = 0;

     while(!response.equals("Q")) {

        response = response.toUpperCase();

        switch(response) {
            case("P"):

            //System.out.println("1 = Song 1, 2 = Song 2");
            //System.out.println("Enter Your Song Choice: ");

                switch(response2) {

                    case("1"):
                    clip.stop();
                    audioStream = AudioSystem.getAudioInputStream(song1);
                    clip = AudioSystem.getClip();
                    clip.open(audioStream);
                    break;

                    case("2"):
                    clip.stop();
                    audioStream = AudioSystem.getAudioInputStream(song2);
                    clip = AudioSystem.getClip();
                    clip.open(audioStream);
                    break;

                    default: System.out.println("Not a valid song response, I'll play 
the default song instead...hahahaha!!!");
                }

            clip.start();
            
            pause = 0;
            break;

            case("S"): clip.stop();
            pause = 0;
            break;

            case("R"): clip.setMicrosecondPosition(0);
            pause = 0;
            break;

            case("K"): 
            if (pause == 0) {
            pause = 1;
            position = clip.getMicrosecondPosition();
            clip.stop();
            System.out.println("You paused!");
            break;
            }

            if (pause == 1) {
                pause = 0;
                clip.setMicrosecondPosition(position);
                clip.start();
                System.out.println("You unpaused!");
                break;
            }

            case("Q"): clip.close();
            break;
            
            default: System.out.println("Not a valid action response");
        }

    }

    System.out.println("You quit the program! Thanks for using Rohan's media player! 
Thanks to Bro Code for helping me code this!!!!");

}

}

And the other class which has the GUI and feeds the actions:

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.io.IOException;

import java.awt.event.ActionEvent;

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

import javax.swing.*;

public class myFrame implements ActionListener {

static int timesAnswered = 0;

String answer1;
String answer2;

static JButton button;

static JTextField field;

static JLabel label;

myFrame() {

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    JFrame frame = new JFrame();
    frame.setSize(250, 250);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setTitle("Rohan's Media Player... jk just audion ):");
    frame.setResizable(false);

    frame.add(panel);

    button = new JButton("ENTER");
    button.setPreferredSize(new Dimension(150, 50));
    button.addActionListener(this);

    field = new JTextField();
    field.setPreferredSize(new Dimension(150, 50));

    label = new JLabel("P = Play, S = Stop, R = Reset, Q = Quit, K = toggle pause");
   
    panel.add(label);
    panel.add(field);
    panel.add(button);

    frame.setVisible(true);

}

@Override
 public void actionPerformed(ActionEvent e) {

   if (timesAnswered == 0) {

        answer1 = field.getText();
        label.setText("1 = Song 1, 2 = Song 2");
        timesAnswered = 2;
        return;
        
    }
    if (timesAnswered == 2) {

        label.setText("P = Play, S = Stop, R = Reset, Q = Quit, K = toggle pause");
        answer2 = field.getText();
        timesAnswered = 1;

        try {
            Main.playMusic(answer1, answer2);
        } catch (UnsupportedAudioFileException e1) {
           
            e1.printStackTrace();
        } catch (IOException e1) {
            
            e1.printStackTrace();
        } catch (LineUnavailableException e1) {
          
            e1.printStackTrace();
        } 
    }
   
   
} 

}

  • 1. You never appear to use the Scanner in any way. 2. You're mixing a console application and a Swing GUI -- why? Doing this is almost a guarantee of misery, and you're much better off using either one or the other, not both. – Hovercraft Full Of Eels Aug 12 '23 at 01:50
  • This code's while (true) loop looks like it will result in a frozen GUI. Is this what happens? If so, again, don't combine a console app with an event-driven app. – Hovercraft Full Of Eels Aug 12 '23 at 01:51
  • Honestly, it looks like you're trying to use code copied from some source in your program, and if so, don't. Instead, learn what the found code is doing, and then re-write your own code, code that will work well with your own program, rather than just copying and pasting the found code. – Hovercraft Full Of Eels Aug 12 '23 at 01:53
  • So in sum: 1) don't use a `while (true)` loop in an event-driven GUI, not unless you have no other choice (here you do have other options) and not unless you fully understand how to do background threading in that GUI library. 2) Never borrow code, but instead, borrow *ideas* that you find in code. 3) Trying to learn coding via YouTube videos will only bring frustration as there is no quality control for these videos and most is shear dreck. – Hovercraft Full Of Eels Aug 12 '23 at 01:57
  • @HovercraftFullOfEels ok thank you. I did use a tutorial on how to play audio as the subject is entirely new to me, but other than that, it's my code. Also, the tutorial uses the Scanner class because, as the tutorial said, Java likes to skip over the clip.play() method, and they use the scanner class to make it fully play the song/audio. Do you know any workaround to this? As in, do you know a way to make java fully play the audio without skipping it, going to the top of the while loop and repeating? – Rohan Prabhala Aug 12 '23 at 02:11
  • @HovercraftFullOfEels And yes, the GUI is getting frozen, I assumed I had to use threads but threads is an entirely new subject to me too. – Rohan Prabhala Aug 12 '23 at 02:11
  • Here's a [method](https://stackoverflow.com/questions/2416935/how-to-play-wav-files-with-java/74965929#74965929) to play WAV files used in a Java Swing application. Here's the [Java Swing application](https://github.com/ggleblanc2/announce-time#readme) that uses the method. – Gilbert Le Blanc Aug 12 '23 at 02:40

0 Answers0