直接从字节数组播放声音 - 的Java [英] 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;
}
}
这是一种很难解释什么错。我得到了完善,但它只有像噪声的旋风-kind。
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.
我想,因为我的整个应用程序是围绕它建成使用此方法字节的缓冲区等。使用剪辑或的AudioInputStream是不是一个真正的选择。
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.
所以我想我的问题是:
如何使用一个字节的缓冲区直接播放的声音从我的字节数组?
感谢您的帮助!
推荐答案
我已经成功地使其工作。这是我的新的code:
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;
}
}
这可能看起来像播放声音就像使用一个的AudioInputStream复杂的方式,但现在我能做到在每个tick ++并通过这样做,我可以介入,如果我需要,以确切的时间计算。
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.
此外,它听起来非常扭曲的原因是,它似乎像的ByteBuffer彻底改变了我的采样值。是什么原因我也不知道。如果有人知道,请让我知道!
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!
感谢您。 :)
这篇关于直接从字节数组播放声音 - 的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!