Search code examples
javaaudioaudioinputstream

How to stop audio through clips with a seperate method


So this is my code. I have it in a seperate class, so I can simply call start and stop music and what I'm trying to do is actually find a way to stop the music, by calling the stopMusic method. I have no clue how to work with clips and InputStreams so I'm not sure of any way to actually implement what I'm trying to do. (Edit: I should mention that none of this code is mine so im not familiar with it, I was trying to find a way to implement audio into my game and found a helpful tutorial)

import java.io.IOException;

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;
import javax.swing.JOptionPane;

public class musicStuff {

    void playMusic (String musicLocation)
    {
        try
        {
            File musicPath = new File(musicLocation);
            
            if (musicPath.exists())
            {
                AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
                Clip clip = AudioSystem.getClip();
                clip.open(audioInput);
                clip.start();
                clip.loop(Clip.LOOP_CONTINUOUSLY);
            }
            else 
            {
                System.out.println("Can't find file");
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
    void stopMusic (String musicLocation)
    {
    
        
    }
    
}

//If anyone can help me with this I'd appreciate it

Solution

  • The Clip should be an instance variable, otherwise, you won't have a way to access it in your stopMusic() method.

    From the API for Clip, observe that there is a start() and stop() method (associated with DataLine). It's generally a good practice to initialize and open the Clip for playback in its own method, and then have separate methods for starting and stopping. When you stop, you might want to change the position of the cursor to the first frame (setFramePosition(0)) so that when you restart, the music starts from the beginning of the Clip.