停止播放歌曲

时间:2013-10-16 21:31:14

标签: java javasound

我的服务器需要帮助。我收到某些消息后成功播放歌曲,但是当我收到停止时它会停止播放该歌曲,但会使服务器崩溃。我提前感谢你的帮助

    public class server
{
    private static final int PORT = 7777;

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;


    @SuppressWarnings("unused")
    private String filename;  
    private static  Clip clip4;
    static Player player; 

    public server(String filename) {  
        this.filename = filename;  


    }
    public static void main(String[] args) throws Exception

    {


        try
        {
            serverSocket = new ServerSocket(PORT, 0, InetAddress.getLocalHost());

            System.out.println("IP:  " + serverSocket.getInetAddress() + "  Port:  " +  serverSocket.getLocalPort());

        } catch (IOException e)
        {
            System.out.println("Could not listen on port: 7777");
        }

        System.out.println("Server started. Listening to the port 7777");

        while (true)
        {

            try
            {
                clientSocket = serverSocket.accept();
                inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader); 
                message = bufferedReader.readLine();


                System.out.println(message);{
                clip4 = null;
     if (message.equals("rock1")) {

                    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("D:/Andrd/Music/TheAll-AmericanRejects-Swing,Swing.wav"));
                      clip4 = AudioSystem.getClip();
                      clip4.open(inputStream);
                      clip4.start(); 

                } else if (message.equals("stop") && clip4 = null && clip4.isRunning()){
                     clip4.stop();
                 }
 }


                inputStreamReader.close();
                clientSocket.close();


            }catch (IOException ex)
            {
                System.out.println("Problem in message reading");
            }


        } 
        }

}

这是执行此代码后我的控制台的样子

 IP:  Timskie-PC/192.168.1.118  Port:  7777
    Server started. Listening to the port 7777
    rock1
    stop

但仍然没有停止歌曲

1 个答案:

答案 0 :(得分:0)

试试这个:

Clip clip4 = null; // Make this a member variable.
...
if (message.equals("rock1")) {
  AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("D:/Andrd/Music/TheAll-AmericanRejects-Swing,Swing.wav"));
  clip4 = AudioSystem.getClip();
  clip4.open(inputStream);
  clip4.start();
} else if (message.equals("stop") && clip4 != null && clip4.isRunning())
  clip4.stop();
}

修改

请注意Clip clip4 = null;不是成员变量。它在while循环中声明。每次循环迭代时,它都被重新声明。如果将其声明为类级“成员变量”,则会得到不同的结果。