alxcyl
alxcyl

Reputation: 2722

Effectively playing .wav files in JAVA

I am writing a program that can play .wav files with a click of a button. Currently, I've been doing it like this:

  1. Load/Open file.
  2. Play file.
  3. Close file.

This happens in a separate thread.

This works quite well and I have no problems doing it but I've read somewhere that loading the files each time they are needed can potentially slowdown the program and may cause all sorts of troubles. They said it is smarter to put these files in a cache but I'm not sure how to do that (I think I read that in StackOverflow too but I'm not too sure).

Thanks in advance.

Upvotes: 0

Views: 169

Answers (1)

Thomas
Thomas

Reputation: 88747

It depends how you play the file but assuming you load the file as a byte stream you'd just store the contents of the file as a byte array and put it into the cache.

When loading the file again you retrieve the byte array from the cache and create an input stream from it.

Something like this pseudo code:

byte[] cachedFile = cache.get(filename);
if( cachedFile != null ) {
   cachedFile = loadFile( filename);
   cache.put( filename, cachedFile );
}

InputStream stream = new ByteArrayInputStream(cachedFile);
play(stream);

Note that this is just some basic approach, you'd need to add synchronization to the cache access, exception handling, cache eviction strategies (if the cache might get too big) etc.

Besides that you might look into memory mapping the files which provides a tradeoff: You don't have to read the entire file before playing it but read the stream directly while playing. Thus you'd only read the parts that the player needs. This might still be slower than in-memory data due to lower hard disk throughput but that might not even be noticable since you only need a certain amount of data from the file at a given time. With this approach you wouldn't need a cache and you'd reduce memory requirements.

Upvotes: 3

Related Questions