Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to preload sound into memory to improve performance?

843802Aug 21 2007 — edited Aug 21 2007
Hello all
I have an application where it needs to play 4 different short wave files on some events. The wave files are small (less then 1 sec each) so they can be preloaded into memory. But I don't really know how to do that.. This is my current code... Performance is really important here, so the faster users can hear the sounds, the better...
import java.io.*;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.event.*;

public class PlaySound implements ActionListener
{
	private Clip clip = null;
		
	public void play(String name)
	{
		if (clip != null)
		{
			clip.stop();
			clip = null;
		}
		loadClip(name);
		clip.start();
	}
	
	private void loadClip(String fnm)
	{
		try 
		{
			AudioInputStream stream = AudioSystem.getAudioInputStream(new File(fnm + ".wav"));
			AudioFormat format = stream.getFormat();
			DataLine.Info info = new DataLine.Info(Clip.class, format);
			if (!AudioSystem.isLineSupported(info)) 
			{
				JOptionPane.showMessageDialog(null, "Unsupported sound line", "Warning!", JOptionPane.WARNING_MESSAGE);
			}
			else
			{
				clip = (Clip) AudioSystem.getLine(info);
				clip.open(stream);
				stream.close();
			}
		}
		
		catch (Exception e) 
		{
			JOptionPane.showMessageDialog(null, "loadClip E: " + e.toString(), "Warning!", JOptionPane.WARNING_MESSAGE);
		}
	}
	
	public static void main(String[] args)
	{
		play("a wav file name");
	}
}	
I would appreciate it if someone can point out how I can preload them to improve performance... Thanks in advance!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 18 2007
Added on Aug 21 2007
3 comments
405 views