admin管理员组文章数量:1416642
I'm wondering if it's possible to constantly output audio generated on the fly to a DataLine
, e.g. so the sound changes in response to some kind of state like user input. I'm at a point where I can write indefinitely to the line, but I am just constantly writing nonstop rather than as needed to keep only a short buffer of extra audio written. Is there an approach to do so, other than perhaps just calling Thread.sleep
in the loop for the duration of the buffer?
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.sound.sampled.*
import kotlin.math.PI
import kotlin.math.sin
const val SAMPLING_RATE = 44100F
const val BITS16 = 16
const val STEREO = 2
val format = AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
SAMPLING_RATE,
BITS16,
STEREO,
BITS16 * STEREO / 8,
SAMPLING_RATE * BITS16 * STEREO / 8,
false)
const val BUFFER_SIZE = 4096
var phase = 0F
fun generateBuffer(n: Int, buffer: FloatBuffer) {
// Some potentially state-sensitive audio generation procedure. Generating a pure sine as an example.
repeat(n) {buffer.put(sin((phase + it * 2 * PI * 440 / 44100F).toFloat()))}
phase += (n * 2 * PI * 440 / 44100F).toFloat()
}
fun main() {
val dataLineInfo = DataLine.Info(
SourceDataLine::class.java,
format)
val dataLine = AudioSystem.getLine(dataLineInfo) as SourceDataLine
dataLine.open()
val byteBuffer = ByteBuffer.allocate(2 * 2 * BUFFER_SIZE).order(ByteOrder.LITTLE_ENDIAN)
val intBuffer = byteBuffer.asIntBuffer()
val floatBuffer = FloatBuffer.allocate(BUFFER_SIZE)
dataLine.start()
// This just generates and writes data nonstop. Can I generate chunks of audio on-demand as they are exhausted?
while (true) {
floatBuffer.rewind()
generateBuffer(BUFFER_SIZE, floatBuffer)
floatBuffer.rewind()
intBuffer.rewind()
repeat(BUFFER_SIZE) { intBuffer.put((floatBuffer.get() * 32767).toInt()) }
dataLine.write(byteBuffer.array(), 0, 2 * 2 * BUFFER_SIZE)
}
}
本文标签: javaRealtime generation of audio to write to SourceDataLineStack Overflow
版权声明:本文标题:java - Realtime generation of audio to write to `SourceDataLine` - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745254810a2650037.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论