Javax.sound.sampled - Writie PCM audio samples to an AIFF file?

Greetings,
I've been going at this for awhile and seem to be stuck.
I'm importing data from an old system that stored audio recordings in raw PCM. I can easily use a Clip object to convert that PCM into a DataLine (Clip) object and play it.
Now I need to write out that audio data as an AIFF file (actually I need to capture it and store it in a database, but the AIFF file format seems like a good, portable, format).
To write a file using AudioSystem.write() you need an AudioInputStream. To create an AudioInputStream you need a TargetDataLine. However, I can see no direct way of creating a TargetDataLine that can be populated with raw data.
Reading the documention (I know, it's a bad habit), it seems like what I needed to do is get a mixer, create a SourceDataLine with my data, then pump the SourceDataLine with the audio samples. The mixer would do nothing but pass the data on to the TargetDataLine where it would be captured and written to disk. Here's my code:
public void writeAIFF( OutputStream out ) throws IOException
try
// First, find a mixer (we assume it will be a software mixer) that can provide us with
// both source and target datalines that can handle the desired format.
AudioFormat format = getAudioFormat(); // This is the format of our data
DataLine.Info sourceInfoRequest = new DataLine.Info(SourceDataLine.class,format);
DataLine.Info targetInfoRequest = new DataLine.Info(TargetDataLine.class,format);
Mixer ourMixer = null;
// Get all of the available mixers
Mixer.Info[] info = AudioSystem.getMixerInfo();
for (int i=0; i<info.length; i++)
Mixer mixer = AudioSystem.getMixer(info);
if (mixer.isLineSupported(sourceInfoRequest) && mixer.isLineSupported(targetInfoRequest))
ourMixer = mixer;
break;
if (ourMixer==null)
throw (new IOException("can't obtain audio components"));
// Get the source and target lines from the mixer
SourceDataLine sourceLine = (SourceDataLine)ourMixer.getLine(sourceInfoRequest);
TargetDataLine targetLine = (TargetDataLine)ourMixer.getLine(targetInfoRequest);
AudioInputStream targetStream = new AudioInputStream(targetLine);
// Load up the source line with the data
sourceLine.open(format);
sourceLine.write(samples,0,samples.length);
// Write our data out as an AIFF file
AudioSystem.write(targetStream,AudioFileFormat.Type.AIFF,out);
// So what happens to all of these lines and mixers when we're done?
catch ( LineUnavailableException noline )
throw (new IOException("audio line unavailable: "+noline.getMessage()));
My problem is that the code never finds a mixer. The statement (mixer.isLineSupported(sourceInfoRequest) && mixer.isLineSupported(targetInfoRequest)) is always false.
So here's my question (finally): Am I going about this the right way? My other thought is just to create my own TargetDataLine object and populate it with the data myself.
Any thoughts or suggestions?
P.S. I hope this is the right place for this question -- this is the first time I've used this forum
P.P.S. Java 1.3.1 (MacOS X and Windows 2000)

Solved -
This was way over engineered! Overlooked in my reading was a constructor for an AudioInputStream that can use any input stream as it's source.
This was all I needed:
     AudioFormat format = getOurAudioFormat();               // Get the format of our audio data
     AudioInputStream targetStream = new AudioInputStream(new ByteArrayInputStream(samples),format,samples.length);
     AudioSystem.write(targetStream,AudioFileFormat.Type.AIFF,out);

Similar Messages

  • Playing big AudioInputStream whit javax.sound.sampled

    Hello!.
    I've a problem, I've a big AudioInputStream (retrieved from DataBase), and when I try play It with Clip throws this Exception:
    javax.sound.sampled.LineUnavailableException: Failed to allocate clip data: Requested buffer too large.
         at com.sun.media.sound.MixerClip.implOpen(MixerClip.java:536)
         at com.sun.media.sound.MixerClip.open(MixerClip.java:161)
         at com.sun.media.sound.MixerClip.open(MixerClip.java:249)
         at ClipPlayer.<init>(ClipPlayer.java:138)
         at ClipPlayer.main(ClipPlayer.java:192)
    Help Me please, friends.
    Thank's.

    Is funny, but I now know what's the problem.
    For play big AudioInputStream exists a interface in sampled package for play this files. This interface is SourceDataLine. The next code solve the problem:
    AudioInputStream audio=DataBase.retrieveAudioInputStream();
    AudioFormat af=DataBase.retrieveAudioFormat(); // This need's for
    // reconstruct the audiofile
    DataLine.Info datalineinfo=new DataLine.Info(SourceDataLine.class,af);
    try
    if (AudioSystem.ifLineSupported(datalineinfo))
    SourceDataLine source=(SourceDataLine) AudioSystem.getLine (datalineinfo);
    int total=audio.available();
    source.open(af);
    int buffersize=source.getBufferSize();
    byte [] data=new byte[buffersize];
    source.start();
    int read=buffersize;
    //Well, now play!!!
    while (read<total)
    read=audio.read(data,0,data.length);
    if (read==-1) break; //End of audiostream.
    source.write(data,0,read);
    else
    System.err.println("DataLine not supported");
    catch (.....)
    Handle exceptions....
    That's all rigth.!!

  • Best practices for using javax.sound.sampled.Clip?

    I've got a very simple Swing-based puzzle game. When the user performs certain actions, I want to play a trivial little sound. So far, I'm using the Java Sound API (javax.sound.sampled). When the actionPerformed method is called, my model is updated, which triggers an event in the same thread, and one of the listeners, plays a sound like this:
    this.clip.setFramePosition(0);
    this.clip.start()The clip had been previously initialized like this:
              InputStream in = null;
              AudioInputStream ain = null;
              Clip tempClip = null;
              try {
                   in = BubblePopSound.class.getResourceAsStream("pop2.wav");
                   ain = AudioSystem.getAudioInputStream(in);
                   try {
                        DataLine.Info info = new DataLine.Info(Clip.class, ain
                                  .getFormat());
                        tempClip = (Clip) AudioSystem.getLine(info);
                        tempClip.open(ain);
                   finally {
                        ain.close();
              catch(UnsupportedAudioFileException uafe) {
                   // TODO Log that sound own't be played
              catch(LineUnavailableException lue) {
                   // TODO Log that sound own't be played
              catch(IOException ioe) {
                   throw new RuntimeException("IOException reading sound clip", ioe);
              finally {
                   if(ain != null) try {
                        ain.close();
                   catch(IOException ioe) {}
                   if(in != null) try {
                        in.close();
                   catch(IOException ioe) {}
              this.clip = tempClip;So my goal was to load the clip once, and be able to trigger the playing of it repeatedly. Hoever, it only works intermittently. Reading through the http://www.jsresources.org site, the Java Sound homepage, forums, etc. I feel like I don't truly understand the best way to play simple audio clips like this. These questions are still lingering:
    - When I call clip.start(), does it play in the current thread, or am I triggering something to start the playing independent of the thread?
    - Do I need to call stop explicitly?
    - What if the user triggers the sound again before it has finished playing?
    - Do I need to close the clip with the playing has stopped, or is it ok to keep it "open" so its ready to play again and again?
    - If I can keep it open, do I need to worry about cleaning it up later?

    If your sound file is < 1 second long and you are using the JDK/JRE 1.5.0 (pre _02 update I think) then the sound code is bugged and is likely the cause of the sound problem. Try updating your JRE/JDK to 1.5.0_03 and try the sound again. If that's not it I can't help.
    - When I call clip.start(), does it play in the current thread, or am I triggering something to start the playing independent of the thread?Not quite sure, but it doesn't seem to be interrupted when I start playing a sound and sleep the thread. It might buffer the sound data in the sound card or it might use a different thread. (Interesting to know if someone has that knowledge...)
    - Do I need to call stop explicitly?No.
    - What if the user triggers the sound again before it has finished playing?It should play the new sound as well (but when many are going some might be cut off. It functions adequately for my game (check out Javoids on sourceforge -- need latest JRE or JDK).
    - Do I need to close the clip with the playing has stopped, or is it ok to keep it "open" so its ready to play again and again?Don't bother. Use this instead "clip.setFramePosition(0);"
    - If I can keep it open, do I need to worry about cleaning it up later?Java is garbage collected so you rarely have to be worried about that. No.

  • How to play a wav file to LINE_OUT with javax.sound.sampled

    Hello all,
    I need to play a wav file to LINE_OUT port, but not to the SPEAKER. I am trying to do this under window NT. For some reason I get false for isLineSupported(Port.Info.LINE_OUT). I am new to javax.sound so I might be doing something wrong. Here is the code that I am using to iterate through all availible mixers and check if LINE_OUT is supported by any of them:
    Mixer.Info[] mixers = AudioSystem.getMixerInfo();
    for(int i = 0; i < mixers.length; i++){
    Mixer mixer = AudioSystem.getMixer(mixers);
    if (mixer.isLineSupported(Port.Info.LINE_OUT)) {
    System.out.println("the port is supported");
    try {
    Port line = (Port) AudioSystem.getLine(
    Port.Info.LINE_OUT);
    catch(Exception ex){
    ex.printStackTrace();
    else{
    System.out.println("the port is not supported");
    Please help

    The new bugID of the request to implement Ports is: 4558938.
    (If you voted for the old bug id: 4504642, be sure to change your votes to this new bug report since the old one was closed as a duplicate of the new one.)

  • Can audio be captured as .aiff file when capturing DV?

    I have set up my System Settings so that I can open audio files into an external editor (a sound editing program called Peak). Any added audio tracks in my FCE file work fine with this because they are .aiff files. But the live audio track that was recorded with the camera is apparently a Quicktime file, and won't open in Peak. Someone told me that I could set up some sort of preference for capturing DV so that the audio portion would be captured as.aiff. Does anyone know how to do this?
    Thanks, Bob

    i have just tried out your method, Al and Tom, purely in the spirit of experimentation and a strange thing has occurred.
    I had a 30 minute clip but only wanted to manipulate a short section so I put In and Out points yet the whole clip appeared in my sound editor.
    Then (in the timeline) I used the razor blade to cut out and delete the unwanted sections, but again the whole audio clip appeared in the editor.
    Is it only possible to open the complete audio clip?
    Ian.

  • Record my voice using JAVAX.sound

    I want to record my voice using the javax.sound.
    Can you please give if there shortest path..
    I see javax.sound.sampled.AudioSystem
    But the sampled is confusing me.. is it a beta version and need to be developed further?
    After recording, I am interested to parse the voice.

    Hmm interesting ones, I've never programmed sound using Java myself, but have you looked at http://docs.oracle.com/javase/6/docs/technotes/guides/sound/programmer_guide/contents.html ? It seems like a good doco to get started

  • Where's javax.sound

    Hi
    i've downloaded j2se 1.4.1 but when i try to import javax.sound.* it says it can't find it. Do i need to import anything else eg java.lang or what? I'm pretty sure its not an optional package.
    Please help me

    You aren't easily distracted from a set opinion, huh?
    You got the same answer from me in that thread:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=32
    334
    You'd have to return to your thread to notice,
    though,
    instead of posting a new one...
    I really appreciate your help docjekill, but even when i specify
    javax.sound.midi
    javax.sound.midi.spi
    javax.sound.sampled
    javax.sound.sampled.spi
    all of these i still get the same error.
    I've looked in scr.zip and found other packages, eg javax.swing etc, but no sound packages. Is the download incomplete or did it just stuff up?

  • Where is javax.sound?

    Compiler tells me it doesn't exist, even when setting classpath as follows:
    C:\JDK\bin\javac -classpath C:\JDK\JRC\lib\rt.jar soundApp.java ...
    I have version 1.4.1.

    How old is this application you are trying to use, or how old is the code if you are getting it from another source?
    1.3 through 1.4.1 use javax.sound.midi, javax.sound.midi.spi, javax.sound.sampled, and javax.sound.sampled.spi.
    They dont try to import javax.sound in and of themselves. This may be an old program written back when javax.sound stuff wasnt included in the API and was a part of the Java Media Framework.
    Of course, I could be totally wrong here (as I havent done anything with sound stuff in Java in quite a while.)
    Just a thought.

  • Record sound sample from flash dynamic page

    Hello , I have a basic problem. I visited Emerson Lake and
    Palmers drummer Carl Palmers web page. It is www.carlpalmer.com
    When you enter the site , there appears a drumset picture. When you
    move your cursor without clicking on the drumset , it plays the
    drums. Google group members say it is a flash site . I want to
    record the sound samples at the same quality. How can I do it ? I
    tried some win audio recorder like programs but I could not
    succeed.
    Best ,
    Mustafa Umut Sarac

    Ever think that this may violate copyright law?
    If you have a legitimate use, you might try contacting the
    webmaster of the site and ask for the originals.

  • Creating mp3 sound samples

    Is garageband easy to use to take a CD and create 30 second mp3 sounds samples for a website?

    you could use GB, but my preference for editing audio is an Audio Editor:
    http://www.bulletsandbones.com/GB/GBFAQ.html#audioeditors

  • I'm on OS X 10.6.8 and have a .mov file which plays on QuickTime 10.0 but with choppy video and the sound is out of sync???? File details are Video Codec: DNxHD (AVdn) Resolution 1920x1080 Audio Codec: PCM S24 BE (in24) Bitrate: 1536kb/s Solutions?

    I'm on OS X 10.6.8 and have a .mov file which plays on QuickTime 10.0 but with choppy video and the sound is out of sync???? File details are Video Codec: DNxHD (AVdn) Resolution 1920x1080 Audio Codec: PCM S24 BE (in24) Bitrate: 1536kb/s.  Any ideas?

    Question: Is all the source footage shot in 16 bit audio or is some also shot in 12 bit?
    http://docs.info.apple.com/article.html?artnum=42973
    http://www.kenstone.net/fcphomepage/idvd_6stone.html
    http://docs.info.apple.com/article.html?artnum=93006
    http://docs.info.apple.com/article.html?artnum=303550
    http://docs.info.apple.com/article.html?path=iDVD/6.0/en/397.html
    http://docs.info.apple.com/article.html?artnum=61636
    http://docs.info.apple.com/article.html?artnum=302925

  • Capturing sound samples

    hi , i need the best way to capture sound samples from an opened Microphone port
    is it by directly using a TargetDataLine and how ?
    and thanks

    Hope this program will help you.
    http://www.jsresources.org/examples/SimpleAudioRecorder.java.html

  • Whether / when to convert to PCM audio burning to Blu Ray discs

    I have been exporting FCP Sony HDV sequences as QT self-contained mov files into Toast 10.0.2 and burning via a Lacie BD external burner onto BD-R discs. They look and sound fantastic. But was wondering, I have stayed with the Dolby stereo audio tracks for the process and let the BD player do the down sampling to PCM audio for the HDMI output to my LCD monitor.
    Is there any advantage to my setting the encode to burn PCM audio tracks on the BD-R discs? Will this take longer? (already 25 to 30 hours encoding and burning a 90 minute QT mov file.)

    I think you have it backward.
    PCM tracks are uncompressed. You're compressing to AC3, and your DVD player is playing AC3.
    PCM tracks will leave less bandwidth available for the video.
    If it ain't broke, don't fix it.

  • How Do I Detemine Maximum DVD Time For A PCM Audio DVD

    I have been working with my CS2 Premiere to create some auto play, audio-only DVDs that are autoplay.  To clear the air, yes I know that CS4 will permit 24bit-96 kHz.  For the time being 16 bit-48 kHz will suffice as it has CD quality  The bonus that a DVD format provides a greater playing times.  So the object is to make a PCM audio only DVD.
    Here is my problem: How to get really long playing time.  I know I can make high quality, 2-channel (ordinary stereo)  DVD-A's up to 3 hours using Minatonka Bronze.  Unfortunately, DVD-A discs are worthless as they cannot play in 90% of DVD players, but they prove the time point.  I would think that one should be able to make a conventional DVD, but with the PCM sound format of that same length.
    I just finished one that fit with a 103 minute, 16/48 stereo audio file of 1.11 GB size.   I also had a video file that I created using several photos. Sorry, don't have the final video file size.  I erased it all from my computer.  However, the final disc size was 3.754 GB.  A little extrapolation suggests a maximum DVD length of 119 minutes.  That with simple video and PCM audio.  Now, can one make a similar DVD with 150 minutes?
    I had three 48 kHz files that I created in Adobe Audion.  They were 1.599, 0.911, and 0.974 GBs in size.  That added up to 3.480.  The playing time is about 2:30 Hours; quite a bit less than 3 hours.   I tried burning a DVD with these, audio-files-only.  I checked lowest quality video, used no video, and got an Export To DVD error that I had "insufficient" space on the 4.7 GB disc!  So, I used the two latter files, which added to only 1.884 GB.  Premiere did not baulk, and it successfully burned a DVD that played.  Then I added the 1.599 GB file, and, once again, it produced an error.  This was clearly not going to work.
    At this point, I realized that Audition had done what it liked to do: It had saved the 16 bit-48 kHz files as 32 bit-48 kHz!  So, I went back to Audition and used EDIT to change the files to genuine 16 bit-48 kHz files.  When I opened them in Premiere, Premiere reported 16 bit-48 kHz files.  Their sizes were now, 0.799, 0.456, and 0.487 GB.  Please note that this totals 1.742 GB.  This is less than the 1.884 GB I had successfully used before.   Once again, I was getting the "insufficient" space error.
    I searched the CS2 Premiere manual and its index, but cannot really find any way to calculate maximum times, or squeezing the most out.  So, anybody got some ideas?
    Mike

    When working from DVD-Videos, this ARTICLE might be helpful - All VOB's (the container for the MPEG-2 files in a DVD-Video) are not created equally.
    Most DVR's write a VOB 01, that is not up to the DVD-specs. That can create a problem for PrE (and also PrPro), and if you have issues, please do follow Neale's advice.
    Good luck and welcome to the forum.
    Hunt

  • I recently got new mac air and transferred my old version garageband projects now when I open them in 10.0.2 I can add new tracks but then nothing can record, shows its receiving sound from software inst. but no sound. I checked audio preferences and

    i recently got new mac air and transferred my old version garageband projects now when I open them in 10.0.2 I can add new tracks but then nothing can record, shows its receiving sound from software inst. but no sound. I checked audio preferences and they are set as they should be. I tried it in all the other older projects and same issue anyone have any experience like this very frustrating.  Can one download old version still ? or can you run both versions on OS10.9.5 ?

    Ok, either my question was too long or nobody seems to have an answer. Sad, either way
    Here's something I found out in the meantime, maybe this is interesting for somebody or maybe - problem's not totally solved - enough info for any of you to give me further advice.
    When I start Logic Core Audio driver de-activated, I can open old songs. Then I save them in a new folder with all audio files and a new name. And I remove all EXS24 instruments as well as the Space Designer. I quit Logic, re-open with Core Audio activated and I can open the song.
    Problem no.1: EXS24 instruments don't find the appropriate samples, but EXSMananger Pro did help me with this. Same problem with Space Designer, which doesn't find the impulse responses, connected to a certain preset.
    Two questions, every idea would be great!
    - Is there any way to teach Space Designer Presets where to look for impulse respones. I can load IR samples directly and create a new preset, but I can't use my old ones.
    - Is it possible to install Logic from scratch over an existing version? Or how should I de-install everything connected with Logic and then install a fresh version from CD?
    Thank you again,
    Joern

Maybe you are looking for

  • I don't believe firefox is the issue but for some reason pictures and certain websites will not load correctly. Why?

    ''Duplicate post, continue here - [https://support.mozilla.com/en-US/questions/810160]'' This just started happening a few days ago. When I go to facebook the pictures are distorted and nearly impossible to discern who is in them. I also go to many d

  • Printing problems for a win xp machine

    I have a win XP machine on my airtunes network. i have tried everything under the sun including boujour, but can't send a print job from the XP machine to my printer. The printer is hooked up to the airtunes router. I have a powerbook G4 and power MA

  • Phone won't orient to landscape since ios8

    When I switch my phone from vertical to horizontal, the operating system won't orient.  It takes me shaking the phone up and down to make it work, even then it sometimes doesn't.  I've done hard restarts, I've looked around online, it appears no one

  • Project system: error when confirm an activity

    Hi Gurus, I try to confirm an activity ( TC: CJ20N ). I go through "Edit / Activity / Confirm" but I get following message NO VALID CAPACITY FOR FINITE SCHEDULING (mssg Nr. C7 057). However I already confirmed an activity assigned to the same work ce

  • Weblogic HTTP Sessions timeouts

    Hi All, Im quite new to Weblogic 8.1 and am having a problem with HTTP sessions. I have two applications (lets say App1 and App2) in the same Weblogic server, and want to pass information from App1 to App2. Because of HTTP ServletContext rules, I can