1

So I am new to OOP in general especially with the swing class. My question is that although my code compiles with no error, there is no sound when I play a long sound file of some music. Is there a way to fix this issue because I am using a wave file which is stored in every possible folder I could think of that constitutes to the code. Moreover, is there a specific type of wave format I need since I read some posts about little-endian (I have no clue what that means)...

The code goes to the try block but then "skips" the next four lines as if they were even't there.

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

public class Sound {
    Clip clip = null;

    public Sound(String file) {

        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream(file));
            clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
            System.out.println("Done!");
        } catch (Exception err) {
            err.printStackTrace();
        }
    }
}

If possible in layman's terms. Thanks. :)

NOTE: I will like to stress the fact that I do not wish for answers to implement the sun.audio package because it is apparently "outdated" for Java.

EDIT: I found an awkward solution that used a thread loop: as long as the music is playing, the thread will sleep for 15 seconds.

Ian L
  • 154
  • 8
  • If the execution is skipping the code within the `try` block, that sounds like there is an exception been thrown. How long (in time) is you wave file? – MadProgrammer Jan 12 '16 at 03:46
  • The time is 261 seconds. – Ian L Jan 12 '16 at 03:50
  • I have no issue playing wave files of 5+ mins (300 seconds). Verify the `Sound.class.getResourceAsStream(file)` is not returning `null` – MadProgrammer Jan 12 '16 at 03:53
  • When I used `out.println(audioInputStream)`, it showed the address javax.sound.sampled.AudioInputStream@717e5fde. This could not mean null right? Plus I'm not to sure that the code was actually skipped, but it seemed like it. – Ian L Jan 12 '16 at 03:57
  • I wanted the result of `getResourceAsStream`, but I would imagine that `AudioSystem.getAudioInputStream` would complain about a `null` value – MadProgrammer Jan 12 '16 at 03:59
  • Any suggestions on how to fix this? I tried putting the test.wav file on every single folder in my eclipse project, but no sound has played yet. Is there a better way to play a file? – Ian L Jan 12 '16 at 04:06
  • *"How to play long sound.."* [`BigClip`](http://stackoverflow.com/a/5668510/418556) is one way, though recently I've been using the Java-FX based `MediaPlayer` (which loads the sound source little by little as it needs more, rather than all at once). – Andrew Thompson Jan 12 '16 at 04:25
  • do you hear 'short' sound clips? is your code working with short sound clips? – Martin Frank Jan 12 '16 at 04:50
  • Found a solution though it is a bit awkward. – Ian L Jan 12 '16 at 06:00

1 Answers1

1

This works to render mono (one channel) wav audio using java

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
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 PlayAudio {
    private static boolean tryToInterruptSound = false;
    private static long mainTimeOut = 3000;
    private static long startTime = System.currentTimeMillis();

    public static synchronized Thread PlayAudio(final File file) {

        Thread soundThread = new Thread() {
            @Override
            public void run() {
                try{
                    Clip clip = null;
                    AudioInputStream inputStream = null;
                    clip = AudioSystem.getClip();
                    inputStream = AudioSystem.getAudioInputStream(file);
                    AudioFormat format = inputStream.getFormat();
                    long audioFileLength = file.length();
                    int frameSize = format.getFrameSize();
                    float frameRate = format.getFrameRate();
                    long durationInMiliSeconds = 
                            (long) (((float)audioFileLength / (frameSize * frameRate)) * 1000);

                    clip.open(inputStream);
                    clip.start();
                    System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound started playing!");
                    Thread.sleep(durationInMiliSeconds);
                    while (true) {
                        if (!clip.isActive()) {
                            System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound got to it's end!");
                            break;
                        }
                        long fPos = (long)(clip.getMicrosecondPosition() / 1000);
                        long left = durationInMiliSeconds - fPos;
                        System.out.println("" + (System.currentTimeMillis() - startTime) + ": time left: " + left);
                        if (left > 0) Thread.sleep(left);
                    }
                    clip.stop();  
                    System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound stoped");
                    clip.close();
                    inputStream.close();
                } catch (LineUnavailableException e) {
                    e.printStackTrace();
                } catch (UnsupportedAudioFileException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound interrupted while playing.");
                }
            }
        };
        soundThread.setDaemon(true);
        soundThread.start();
        return soundThread;
    }

    public static void main(String[] args) {

        Thread soundThread = PlayAudio(new File("/home/scott/Dropbox/Documents/data/audio/Elephant_sounds_mono_rgUFu_hVhlk.wav"));
        System.out.println("" + (System.currentTimeMillis() - startTime) + ": playSound returned, keep running the code");
        try {   
            Thread.sleep(mainTimeOut );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (tryToInterruptSound) {
            try {   
                soundThread.interrupt();
                Thread.sleep(1); 
                // Sleep in order to let the interruption handling end before
                // exiting the program (else the interruption could be handled
                // after the main thread ends!).
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("" + (System.currentTimeMillis() - startTime) + ": End of main thread; exiting program " + 
                (soundThread.isAlive() ? "killing the sound deamon thread" : ""));
    }
}

for now the input wav filename is hardcoded ... enjoy

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104