Playing a sound from java?

Supporting Java SE version 7 and up
jamesf
Fresh meat
Posts: 4
Joined: Wed Nov 30, 2011 2:13 pm
Contact:

Playing a sound from java?

Postby jamesf » Mon Jan 09, 2012 8:36 am

Has anyone had any success playing a sound in java using the standard java libraries with the SBC and the USB audio adapter?

Anyone got any pointers?

anewsome
Phidgeteer!
Posts: 54
Joined: Thu Jul 07, 2011 1:43 pm
Contact:

Re: Playing a sound from java?

Postby anewsome » Wed Mar 21, 2012 8:17 pm

I'm getting ready to implement this in my software. I need to play entire songs though so my strategy might be a bit overkill for playing simple sounds.

See my latest post in the general forum. That's my software that I'm adding sound too.

anewsome
Phidgeteer!
Posts: 54
Joined: Thu Jul 07, 2011 1:43 pm
Contact:

Re: Playing a sound from java?

Postby anewsome » Thu Mar 22, 2012 11:09 am

I added the capability to play short clips to my application. You can't play a full length song this way though. This is the code I used:

Code: Select all

import java.io.File;

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;

public class ClipPlay {
    private Clip clip = null;
   
    public ClipPlay()  throws Exception {
       
        File soundFile = new File("../audio/reminder.wav");
        AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

        DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
        clip = (Clip) AudioSystem.getLine(info);
        clip.open(sound);

        clip.addLineListener(new LineListener() {

        @Override
        public void update(LineEvent event) {
            if (event.getType() == LineEvent.Type.STOP) {
              event.getLine().close();
           
            }
          }
        });

    }
   
    public void play() {
        clip.start();
    }
   
   
}


In my application this is what I do to use it:

Code: Select all

private ClipPlay myClipPlay;
try { myClipPlay = new ClipPlay(); } catch (Exception ex) { System.out.println("Problem loading audio clip"); };
myClipPlay.play();


I didn't write this code. I found it on the Internet. It works though. It's only temporary in my application though because I need to play back very long audio files. That requires a buffered reader approach.


Return to “Java”

Who is online

Users browsing this forum: No registered users and 0 guests