?
Solved

Question about javax.sound.sampled.*;

Posted on 2005-04-20
15
Medium Priority
?
236 Views
Last Modified: 2010-03-31
Hello,

When I run this example to play a .wav file, the file runs but after the java console will not end and the sound card cannot be used.

Could advise where I should play the stream.close() and clip.close();

Thanks

try {
        // From file
        AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));
   
        // From URL
        stream = AudioSystem.getAudioInputStream(new URL("http://hostname/audiofile"));
   
        // At present, ALAW and ULAW encodings must be converted
        // to PCM_SIGNED before it can be played
        AudioFormat format = stream.getFormat();
        if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
            format = new AudioFormat(
                    AudioFormat.Encoding.PCM_SIGNED,
                    format.getSampleRate(),
                    format.getSampleSizeInBits()*2,
                    format.getChannels(),
                    format.getFrameSize()*2,
                    format.getFrameRate(),
                    true);        // big endian
            stream = AudioSystem.getAudioInputStream(format, stream);
        }
   
        // Create the clip
        DataLine.Info info = new DataLine.Info(
            Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
        Clip clip = (Clip) AudioSystem.getLine(info);
   
        // This method does not return until the audio file is completely loaded
        clip.open(stream);
   
        // Start playing
        clip.start();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    } catch (LineUnavailableException e) {
    } catch (UnsupportedAudioFileException e) {
    }
 
0
Comment
Question by:EmailSurfer
  • 8
  • 7
15 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 13826963
Try putting those calls in a finally block
0
 

Author Comment

by:EmailSurfer
ID: 13826983
I am quite sure what you meant by a final block.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 140 total points
ID: 13827055
           AudioInputStream stream = null;
            Clip clip = null;
            try {
                  // From file
                  stream = AudioSystem.getAudioInputStream(new File(
                              "audiofile"));

                  // From URL
                  stream = AudioSystem.getAudioInputStream(new URL(
                              "http://hostname/audiofile"));

                  // At present, ALAW and ULAW encodings must be converted
                  // to PCM_SIGNED before it can be played
                  AudioFormat format = stream.getFormat();
                  if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format
                                    .getSampleRate(), format.getSampleSizeInBits() * 2, format
                                    .getChannels(), format.getFrameSize() * 2, format.getFrameRate(),
                                    true); // big endian
                        stream = AudioSystem.getAudioInputStream(format, stream);
                  }

                  // Create the clip
                  DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
                              ((int) stream.getFrameLength() * format.getFrameSize()));
                  clip = (Clip) AudioSystem.getLine(info);

                  // This method does not return until the audio file is completely loaded
                  clip.open(stream);

                  // Start playing
                  clip.start();
            } catch (Exception e) {
                  e.printStackTrace();
            }
            finally {
                  clip.close();
                  try  { stream.close(); } catch(IOException e) { /* ignore */ }
            }
      }
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:EmailSurfer
ID: 13827097
Thanks

I'll just try this.

And will the (finally) lines be used if the program has to throw a exception, and still close the stream, clip?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13827125
Yes
0
 

Author Comment

by:EmailSurfer
ID: 13827130
Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13827182
:-)
0
 

Author Comment

by:EmailSurfer
ID: 13827519
Thanks,

I added the (finally) lines, but found the example will not run the wav file.

Though the other day when tested this the file did run,but the code does not throw any exception.


import java.io.*;
import java.io.File;
import javax.sound.sampled.*;

public class SimpleAudioPlayer{

   static void SimpleAudioPlayer(String clip){
      AudioInputStream      audioInputStream;
      AudioFormat audioFormat;
      DataLine.Info info;
      Clip clips;

      try{
         audioInputStream = AudioSystem.getAudioInputStream(new File(clip));
         audioFormat = audioInputStream.getFormat();

         if((audioFormat.getEncoding() == AudioFormat.Encoding.ULAW) ||
            (audioFormat.getEncoding() == AudioFormat.Encoding.ALAW)){

            AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                                              audioFormat.getSampleRate(),
                                              audioFormat.getSampleSizeInBits()*2,
                                              audioFormat.getChannels(),
                                              audioFormat.getFrameSize()*2,
                                              audioFormat.getFrameRate(),true);

            audioInputStream = AudioSystem.getAudioInputStream(tmp, audioInputStream);
            audioFormat = tmp;
         }

         info = new DataLine.Info(Clip.class, audioInputStream.getFormat(),
                                 ((int) audioInputStream.getFrameLength() *
                                 audioFormat.getFrameSize()));

         clips = (Clip) (AudioSystem.getLine(info));
         clips.open(audioInputStream);
         clips.start();
      }
      catch(Exception e){
      }

      finally{
         clips.close();
         try{
            audioInputStream.close();
         }catch(IOException ex){
         }
      }
   }


   public static void main(String args[]){
      SimpleAudioPlayer("welcome.wav");
   }

}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13827556
You won't see any exceptions as you've ignored them:

>>
    catch(Exception e){
      }
>>

0
 

Author Comment

by:EmailSurfer
ID: 13827688
Thanks

I changed the code, to print out the exception, and then exit.

But found when running the code, no exception was printed and the java session would not end.

import java.io.*;
import java.io.File;
import javax.sound.sampled.*;

public class SimpleAudioPlayer{

   static void SimpleAudioPlayer(String clip){
      AudioInputStream     audioInputStream;
      AudioFormat audioFormat;
      DataLine.Info info;
      Clip clips;

      try{
         audioInputStream = AudioSystem.getAudioInputStream(new File(clip));
         audioFormat = audioInputStream.getFormat();

         if((audioFormat.getEncoding() == AudioFormat.Encoding.ULAW) ||
            (audioFormat.getEncoding() == AudioFormat.Encoding.ALAW)){

            AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                                              audioFormat.getSampleRate(),
                                              audioFormat.getSampleSizeInBits()*2,
                                              audioFormat.getChannels(),
                                              audioFormat.getFrameSize()*2,
                                              audioFormat.getFrameRate(),true);

            audioInputStream = AudioSystem.getAudioInputStream(tmp, audioInputStream);
            audioFormat = tmp;
         }

         info = new DataLine.Info(Clip.class, audioInputStream.getFormat(),
                                 ((int) audioInputStream.getFrameLength() *
                                 audioFormat.getFrameSize()));

         clips = (Clip) (AudioSystem.getLine(info));
         clips.open(audioInputStream);
         clips.start();
      }
      catch(Exception e){
         System.out.println(e.getMessage());
         System.exit(0);      
      }

      finally{
         clips.close();
         try{
            audioInputStream.close();
         }catch(IOException ex){
         System.out.println(ex.getMessage());
         System.exit(0);
         }
      }
   }


   public static void main(String args[]){
      SimpleAudioPlayer("welcome.wav");
   }

}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13827839
I'm not sure that wav files are supported

>> static void SimpleAudioPlayer(String clip)

looks like a constructor. You should call it 'play'

You've also removed the initialization i put in the code
0
 

Author Comment

by:EmailSurfer
ID: 13827884
import java.io.*;
import java.io.File;
import javax.sound.sampled.*;

public class SimpleAudioPlayer{

   static void Play(String clip){
      AudioInputStream     audioInputStream;
      AudioFormat audioFormat;
      DataLine.Info info;
      Clip clips = null;

      try{
         audioInputStream = AudioSystem.getAudioInputStream(new File(clip));
         audioFormat = audioInputStream.getFormat();

         if((audioFormat.getEncoding() == AudioFormat.Encoding.ULAW) ||
            (audioFormat.getEncoding() == AudioFormat.Encoding.ALAW)){

            AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                                              audioFormat.getSampleRate(),
                                              audioFormat.getSampleSizeInBits()*2,
                                              audioFormat.getChannels(),
                                              audioFormat.getFrameSize()*2,
                                              audioFormat.getFrameRate(),true);

            audioInputStream = AudioSystem.getAudioInputStream(tmp, audioInputStream);
            audioFormat = tmp;
         }

         info = new DataLine.Info(Clip.class, audioInputStream.getFormat(),
                                 ((int) audioInputStream.getFrameLength() *
                                 audioFormat.getFrameSize()));

         clips = (Clip) (AudioSystem.getLine(info));
         clips.open(audioInputStream);
         clips.start();
      }
      catch(Exception e){
         System.out.println(e.getMessage());
         System.exit(0);      
      }

      finally{
         clips.close();
         try{
            audioInputStream.close();
         }catch(IOException ex){
         System.out.println(ex.getMessage());
         System.exit(0);
         }
      }
   }


   public static void main(String args[]){
      Play("welcome.wav");
   }

}
0
 

Author Comment

by:EmailSurfer
ID: 13827893
I found the other day, it was playing the wav file.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13827981
Yes. It does support wav file. I'm not sure what's wrong exactly. There are a few gotchas with this sort of thing. Here is one that *does* work. You have to pass it a url as an argument. e.g.

java PlaySoundStream "file:///C|/DOCUME~1/Charles/MYDOCU~1/applause.wav"


import java.io.*;
import java.net.*;
import javax.sound.sampled.*;
import javax.sound.midi.*;

/**
 * This class plays sounds streaming from a URL: it does not have to preload the
 * entire sound into memory before playing it. It is a command-line application
 * with no gui. It includes code to convert ULAW and ALAW audio formats to PCM
 * so they can be played. Use the -m command-line option before MIDI files.
 */
public class PlaySoundStream {
      // Create a URL from the command-line argument and pass it to the
      // right static method depending on the presence of the -m (MIDI) option.
      public static void main(String[] args) throws Exception {
            if (args[0].equals("-m"))
                  streamMidiSequence(new URL(args[1]));
            else
                  streamSampledAudio(new URL(args[0]));

            // Exit explicitly.
            // This is needed because the audio system starts background threads.
            System.exit(0);
      }

      /** Read sampled audio data from the specified URL and play it */
public static void streamSampledAudio(URL url)
        throws IOException, UnsupportedAudioFileException,
               LineUnavailableException
    {
        AudioInputStream ain = null;  // We read audio data from here
        SourceDataLine line = null;   // And write it here.

        try {
            // Get an audio input stream from the URL
            ain=AudioSystem.getAudioInputStream(url);

            // Get information about the format of the stream
            AudioFormat format = ain.getFormat( );
            DataLine.Info info=new DataLine.Info(SourceDataLine.class,format);

            // If the format is not supported directly (i.e. if it is not PCM
            // encoded), then try to transcode it to PCM.
            if (!AudioSystem.isLineSupported(info)) {
                // This is the PCM format we want to transcode to.
                // The parameters here are audio format details that you
                // shouldn't need to understand for casual use.
                AudioFormat pcm =
                    new AudioFormat(format.getSampleRate( ), 16,
                                    format.getChannels( ), true, false);

                // Get a wrapper stream around the input stream that does the
                // transcoding for us.
                ain = AudioSystem.getAudioInputStream(pcm, ain);

                // Update the format and info variables for the transcoded data
                format = ain.getFormat( );
                info = new DataLine.Info(SourceDataLine.class, format);
            }

            // Open the line through which we'll play the streaming audio.
            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(format);  

            // Allocate a buffer for reading from the input stream and writing
            // to the line. Make it large enough to hold 4k audio frames.
            // Note that the SourceDataLine also has its own internal buffer.
            int framesize = format.getFrameSize( );
            byte[  ] buffer = new byte[4 * 1024 * framesize]; // the buffer
            int numbytes = 0;                               // how many bytes

            // We haven't started the line yet.
            boolean started = false;

            for(;;) {  // We'll exit the loop when we reach the end of stream
                // First, read some bytes from the input stream.
                int bytesread=ain.read(buffer,numbytes,buffer.length-numbytes);
                // If there were no more bytes to read, we're done.
                if (bytesread == -1) break;
                numbytes += bytesread;
               
                // Now that we've got some audio data to write to the line,
                // start the line, so it will play that data as we write it.
                if (!started) {
                    line.start( );
                    started = true;
                }
               
                // We must write bytes to the line in an integer multiple of
                // the framesize. So figure out how many bytes we'll write.
                int bytestowrite = (numbytes/framesize)*framesize;
               
                // Now write the bytes. The line will buffer them and play
                // them. This call will block until all bytes are written.
                line.write(buffer, 0, bytestowrite);
               
                // If we didn't have an integer multiple of the frame size,
                // then copy the remaining bytes to the start of the buffer.
                int remaining = numbytes - bytestowrite;
                if (remaining > 0)
                    System.arraycopy(buffer,bytestowrite,buffer,0,remaining);
                numbytes = remaining;
            }

            // Now block until all buffered sound finishes playing.
            line.drain( );
        }
        finally { // Always relinquish the resources we use
            if (line != null) line.close( );
            if (ain != null) ain.close( );
        }
    }
      // A MIDI protocol constant that isn't defined by javax.sound.midi
      public static final int END_OF_TRACK = 47;

      /* MIDI or RMF data from the specified URL and play it */
      public static void streamMidiSequence(URL url) throws IOException,
                  InvalidMidiDataException, MidiUnavailableException {
            Sequencer sequencer = null; // Converts a Sequence to MIDI events
            Synthesizer synthesizer = null; // Plays notes in response to MIDI events

            try {
                  // Create, open, and connect a Sequencer and Synthesizer
                  // They are closed in the finally block at the end of this method.
                  sequencer = MidiSystem.getSequencer();
                  sequencer.open();
                  synthesizer = MidiSystem.getSynthesizer();
                  synthesizer.open();
                  sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());

                  // Specify the InputStream to stream the sequence from
                  sequencer.setSequence(url.openStream());

                  // This is an arbitrary object used with wait and notify to
                  // prevent the method from returning before the music finishes
                  final Object lock = new Object();

                  // Register a listener to make the method exit when the stream is
                  // done. See Object.wait( ) and Object.notify( )
                  sequencer.addMetaEventListener(new MetaEventListener() {
                        public void meta(MetaMessage e) {
                              if (e.getType() == END_OF_TRACK) {
                                    synchronized (lock) {
                                          lock.notify();
                                    }
                              }
                        }
                  });

                  // Start playing the music
                  sequencer.start();

                  // Now block until the listener above notifies us that we're done.
                  synchronized (lock) {
                        while (sequencer.isRunning()) {
                              try {
                                    lock.wait();
                              } catch (InterruptedException e) {
                              }
                        }
                  }
            } finally {
                  // Always relinquish the sequencer, so others can use it.
                  if (sequencer != null)
                        sequencer.close();
                  if (synthesizer != null)
                        synthesizer.close();
            }
      }
}
0
 

Author Comment

by:EmailSurfer
ID: 13828086
I will look over this.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month14 days, 15 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question