java - Realtime generation of audio to write to `SourceDataLine` - Stack Overflow

I'm wondering if it's possible to constantly output audio generated on the fly to a DataLine,

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)
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745254811a4618892.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信