简体   繁体   中英

Play sound directly from byte array - Java

I'm trying to play a sound that is stored as a byte-array using the following method:

byte[] clickSamples = getAudioFileData("sound.wav");
ByteBuffer buffer = ByteBuffer.allocate(bufferSize*2);
int tick = 0;

for (int i = 0; i < clickSamples.length; i++) {
    buffer.putShort((short) clickSamples[i]);
    tick++;
    if (tick >= bufferSize/SAMPLE_SIZE) {
        line.write(buffer.array(), 0, buffer.position());
        buffer.clear();
        tick = 0;
    }
}

It's kind of hard to explain what's going wrong. I'm getting a sound but it's only like a "swoosh"-kind of noise.

I want to use this method with the byte-buffer and so on because my whole application is built around it. Using Clip or AudioInputStream is not really an option.

So I guess my question is:

How can I play sound directly from my byte-array using a byte-buffer?

Thank you for your help!

I've managed to make it work. Here is my new code:

    int tick = 0;
    for (int i = 0; i < clickSamples.length; i++) {
        tick++;
        if (tick >= bufferSize/SAMPLE_SIZE) {
            line.write(clickSamples, i-tick+1, tick);
            buffer.clear();
            tick = 0;
        }
    }

This may seem like a complicated way of playing sound just like with AudioInputStream but now I can do calculations on each tick++ and by doing that I can intervene to exact times if I need to.

If this sounds silly and there is an easier way of doing this, please let me know.

Also, the reason it sounded so distorted is that it seems like ByteBuffer drastically changed my sample-values. For what reason I don't know. If anybody knows, please let me know!

Thank you. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM