Search code examples
javaaudiomp3

Play and Stop sound file according a particular condition checked every 2 secs with java


I consume a service every 2 secs and according its response I want to play or stop a WAVE sound. All seems to work fine (except the overlap of several WAVE executions => but this is not the principal problem), but I cannot stop all the music when condition happens and i don't understand why.

These are my classes

musicStuff.java

package hello;

import java.applet.AudioClip;
import java.io.IOException;
import java.io.InputStream;

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.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JOptionPane;

@SuppressWarnings("deprecation")
public class musicStuff implements AudioClip{

    private Clip clip;
    
    void playMusic(String musicLocation) {
        try {
            InputStream inputStream = getClass().getClassLoader()
                    .getResourceAsStream(musicLocation);
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream);
            Clip clip = AudioSystem.getClip();
            clip.open(audioStream);
            clip.start();
            
        } catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) {
            System.out.println("Error occured during playback process:" + ex.getMessage());
        }

    }
    
    @Override
     public void stop() {
        if (clip == null)
            return;
        clip.stop();
        clip.close();
    }
    
    @Override
    public void loop() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void play() {
        // TODO Auto-generated method stub
        
    }

}

HelloWord.java

package hello;

import java.io.IOException;
import java.util.Date;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.JOptionPane;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HelloWorld {

    public static void main(String[] args) {

        String audioFilePath = "AudioFileWithWavFormat.wav";

        Timer mytimer = new Timer();
        musicStuff player = new musicStuff();
        final TimerTask mytask = new TimerTask() {
            public void run() {
                RestRequest example = new RestRequest();
                String response;
                try {
                    response = example.run("https://webservice.url");
                    if (response.length() > 2) {
                        System.out.println("Yes start play music"); 
                        player.playMusic(audioFilePath);
                    } else {
                        System.out.println("Stop all played music");
                        player.stop();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        };

        int delay = 2;
        mytimer.scheduleAtFixedRate(mytask, delay, delay);

    }

}

Solution

  • Ok I fixed this problem with this code

    musicStuff.java

    package hello;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import javazoom.jl.player.Player;
    
    public class musicStuff {
    
        FileInputStream fileInputStream;
        BufferedInputStream bufferedInputStream;
        
        Thread playThread;
        RestRequest example = new RestRequest();
        int flag_start = 0;
        int flag_stop = 0;
        long totalLength, pauseLength;
        Player player;
    
        public musicStuff() throws InterruptedException {
            // Calling Threads
            playThread = new Thread(runnablePlay);
    
            String response = "";
            while (!response.equals("Q")) {
                try {
                    response = example.run("https://url webservice");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                switch (response) {
                case ("S"):
                    if (flag_start < 1) {
                        playThread = new Thread(runnablePlay);
                        flag_stop = 0;
                        playThread.start();
                        System.out.println("Fai partire la musica");
                    }
                    flag_start = flag_start + 1;
                    break;
                case ("N"):
    
                    if (flag_stop < 1) {
                        flag_start = 0;
                    
                        if (player != null) {
                            player.close();
                            playThread.stop();
                        }
                        System.out.println("Ferma la musica");
                    }
                    flag_stop = flag_stop + 1;
    
                    break;
                default:
                    System.out.println("Errore");
                }
            }
    
        }
    
        Runnable runnablePlay = new Runnable() {
            String audioFilePath = "AudioFileWithMp3Format.mp3";
    
            @Override
            public void run() {
                try {
                    File musicPath = new File(audioFilePath);
                    fileInputStream = new FileInputStream(musicPath);
                    bufferedInputStream = new BufferedInputStream(fileInputStream);
                    player = new Player(bufferedInputStream);
                    totalLength = fileInputStream.available();
                    player.play();//starting music
                } catch (Exception ex) {
                    System.out.println("Error occured during playback process:" + ex.getMessage());
                }
            }
        };
    
    }
    

    HelloWord.java

    package hello;
    
    public class HelloWorld {
    
        public static void main(String[] args) throws InterruptedException {
    
            try {
                musicStuff clip = new musicStuff();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }
    

    I know that I used deprecated playThread.stop() but in this case for me is not a problem. All works correctly :)