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