Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2007

Tip: Looking for answers? Try searching our database.

Java Autio

Thread view: 
phi - 08 Mar 2007 13:09 GMT
Hi all

Is this the right place for Java-Audio Questions?

If so: How do I make java to play an Audio File (eg. WAV).
My Application uses Swing and a Key-Event should play a sound.

Either of the following answers should do:
a) Minimal code Example
b) Link to minimal examples (I have found something on
http://www.jsresources.org/examples/SimpleAudioPlayer.java.html but it
seams rather big for just playing a wave file).

Greetings and thanks in advance
Alex Hunsley - 08 Mar 2007 15:17 GMT
> Hi all
>
[quoted text clipped - 10 lines]
>
> Greetings and thanks in advance

Heard of google? It's a useful website.
Real Gagnon - 09 Mar 2007 02:59 GMT
> Either of the following answers should do:
> a) Minimal code Example
> b) Link to minimal examples (I have found something on
> http://www.jsresources.org/examples/SimpleAudioPlayer.java.html but it
> seams rather big for just playing a wave file).

Simple example at
http://www.exampledepot.com/egs/javax.sound.sampled/StreamAudio.html

and to know more, the Sun tutorial at
http://java.sun.com/docs/books/tutorial/sound/sampled-overview.html

Bye.
Signature

Real Gagnon  from  Quebec, Canada
* Java, Javascript, VBScript or PowerBuilder snippets
* http://www.rgagnon.com/howto.html
* http://www.rgagnon.com/bigindex.html

Knute Johnson - 09 Mar 2007 05:08 GMT
> Hi all
>
[quoted text clipped - 10 lines]
>
> Greetings and thanks in advance

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

public class Play {
    public static void main(String[] args) {
        try {
            AudioInputStream ais =
                AudioSystem.getAudioInputStream(new File(args[0]));
            AudioFormat af = ais.getFormat();
            System.out.println("Format: " + af.toString());

            int frameRate = (int)af.getFrameRate();
            System.out.println("Frame Rate: " + frameRate);
            int frameSize = af.getFrameSize();
            System.out.println("Frame Size: " + frameSize);

            SourceDataLine line = AudioSystem.getSourceDataLine(af);
            line.open(af);
            int bufSize = line.getBufferSize();
            System.out.println("Buffer Size: " + bufSize);

            line.start();

            byte[] data = new byte[bufSize];
            int bytesRead;

            while ((bytesRead = ais.read(data,0,data.length)) != -1)
                line.write(data,0,bytesRead);

            line.drain();
            line.stop();
            line.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

Signature

Knute Johnson
email s/nospam/knute/

Phi - 11 Mar 2007 09:18 GMT
Thank you all

I was looking for somethin like "javax.xxx.SimpleSound.playWave(File
wavFile) throw xxx". But ... no way.
I have found some other resources on google, but the code from Knute
Johnson seams to be the simplest.

Thanks

> Hi all
>
[quoted text clipped - 10 lines]
>
> Greetings and thanks in advance
Phi - 18 Mar 2007 07:25 GMT
Finally solved my problem

I uploaded my audio product under the following web site:
http://www.freimann.eu/eliphi/phi/setzkasten/
The audio - version lies under:
http://www.freimann.eu/eliphi/phi/setzkasten/Setzkasten_sound.jar

Thanks again for all your help

PS The code I finally used is the following:

import java.io.*;
import javax.sound.sampled.*;
import eu.gressly.io.ResourceAnchor;

public class Play {

   public static void playSampleFile(String name, float pan, float
gain) throws Exception{
       InputStream wavInputStream = getWavInputStream(name);
       if(null != wavInputStream) {
           playSampleFile(wavInputStream, pan, gain);
       }
   }

   public static void playSampleFile(String name) throws Exception {
       playSampleFile(name, 0.0f, 0.0f);
   }
/**
* Openes a resource as stream. Adds the directory "/wav/" and the
suffix ".wav" to the given wavName
* TODO: cache input Strams in memory (Hashtable using names as keys and
inputStreams as values.
* if the value is there: reset the stream.
* @param wavName Filename (as resource) without "wav/" and without ".wav"
* @return null or a correctly opened inputStream.
*/

   private static InputStream getWavInputStream(String wavName) {
       ClassLoader cl = ResourceAnchor.class.getClassLoader();
       String resourceName = "wav/" + wavName.toLowerCase() + ".wav";

       return cl.getResourceAsStream(resourceName);
   }

   private static void playSampleFile(InputStream wavInputStream, float
pan, float gain)
           throws Exception {
       AudioInputStream ais =
AudioSystem.getAudioInputStream(wavInputStream);

       AudioFormat format = ais.getFormat();
       // ALAW/ULAW samples in PCM konvertieren
       if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
               || (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
           AudioFormat tmp = new
AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                   format.getSampleRate(), format.getSampleSizeInBits()
* 2,
                   format.getChannels(), format.getFrameSize() * 2, format
                           .getFrameRate(), true);
           ais = AudioSystem.getAudioInputStream(tmp, ais);
           format = tmp;
       }
       // Clip erzeugen und fffffffnen
       DataLine.Info info = new DataLine.Info(Clip.class, format,
((int) ais
               .getFrameLength() * format.getFrameSize()));
       Clip clip = (Clip) AudioSystem.getLine(info);
       clip.open(ais);
       // PAN einstellen
       FloatControl panControl = (FloatControl) clip
               .getControl(FloatControl.Type.PAN);
       panControl.setValue(pan);
       // MASTER_GAIN einstellen
       FloatControl gainControl = (FloatControl) clip
               .getControl(FloatControl.Type.MASTER_GAIN);
       gainControl.setValue(gain);
       // Clip abspielen
       clip.start();
       while (true) {
           try {
               Thread.sleep(300);
           } catch (Exception e) {
               // nothing
           }
           if (!clip.isRunning()) {
               try {
                   Thread.sleep(200);
               } catch (InterruptedException iux) {
               }
               break;
           }
       }
       clip.stop();
       clip.close();
   }

   public static void main(String[] args) {
       try {
           playSampleFile(args[0], Float.parseFloat(args[1]), Float
                   .parseFloat(args[2]));
       } catch (Exception e) {
           e.printStackTrace();
           System.exit(1);
       }
       System.exit(0);
   }
}

> Hi all
>
[quoted text clipped - 10 lines]
>
> Greetings and thanks in advance
Knute Johnson - 18 Mar 2007 18:30 GMT
>         while (true) {
>             try {
[quoted text clipped - 10 lines]
>             }
>         }

You can replace this part with clip.drain().

Signature

Knute Johnson
email s/nospam/knute/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.