Dan Inactive
Dan Inactive

Reputation: 10060

Java: Playing WAV sounds

I am trying to build a java drum machine that needs to play WAV sound samples of the various drum parts (bass drum, snare, etc). Because I need to play the sounds in a tight sequence, I need high performance. Currently I'm using:

import sun.audio.*;
import java.io.*;

public class MusicPlayer {

    private String filename;

    public MusicPlayer(String filename) {
        this.filename = filename;
    }

    public void play() {
        try {
            InputStream in = new FileInputStream(filename);
            AudioStream as = new AudioStream(in);
            AudioPlayer.player.start(as); 

        } catch (IOException e) {
            e.printStackTrace();
        }          
    }
}

as suggested here: How can I play sound in Java?

While it does work faster than MP3 + Javazoom jLayer, it still sounds choppy at high tempo and when I do cpu intensive stuff like resizing the app window.

Any tips on improving performance?

BTW. I've also read that sun.audio.* is deprecated. Is there a similar solution?

Upvotes: 3

Views: 9696

Answers (3)

Gurre
Gurre

Reputation: 11

One thing you could try is to make a couple of extra threads.

If you can play two sounds at once then just make a buffer with 5 instances of the same sound and play the one available.

Upvotes: 1

PhiLho
PhiLho

Reputation: 41132

Perhaps you should put the sounds in cache: if you load them from disk each time you play them, it is indeed slow. Now, you might have a memory problem, but it depends on your sounds (size, number...).

Upvotes: 1

Zach Scrivena
Zach Scrivena

Reputation: 29539

Have you looked at the Java Media Framework (JMF):

The Java Media Framework API (JMF) enables audio, video and other time-based media to be added to applications and applets built on Java technology. This optional package, which can capture, playback, stream, and transcode multiple media formats, extends the Java 2 Platform, Standard Edition (J2SE) for multimedia developers by providing a powerful toolkit to develop scalable, cross-platform technology.

Upvotes: 1

Related Questions