Created
January 25, 2023 14:20
-
-
Save faveoled/f2ad63fce4c7393975d819dbce25751f to your computer and use it in GitHub Desktop.
Scala Native PulseAudio example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import libpulse.functions.pa_simple_new | |
| import libpulse.functions.pa_simple_write | |
| import libpulse.functions.pa_simple_free | |
| import libpulse.types.pa_sample_spec | |
| import libpulse.types.pa_sample_format | |
| import libpulse.types.pa_stream_direction | |
| import libpulse.extern_functions | |
| import scala.scalanative.unsafe | |
| import scala.scalanative.unsafe._ | |
| import scalanative.unsigned.UnsignedRichInt | |
| import scalanative.unsigned.ULong | |
| import java.nio.file.Files | |
| import java.nio.file.Paths | |
| @link("pulse-simple") | |
| object Main { | |
| def readPcm(): Array[Byte] = | |
| Files.readAllBytes(Paths.get("/home/user/Music/Recording6.pcm")) | |
| def makeNativeArray(input: Array[Byte])(using z: Zone): Ptr[Byte] = | |
| if (unsafe.sizeof[Byte] != 1.toUByte) { | |
| throw Exception(s"Byte size is not 1, but ${unsafe.sizeof[Byte]}. Can't proceed") | |
| } | |
| val rawSize = input.length | |
| val buffer = alloc[Byte](rawSize) | |
| for i <- 0 until rawSize | |
| do | |
| buffer(i) = input(i) | |
| buffer | |
| def main(args: Array[String]): Unit = Zone { implicit z => | |
| val spec = pa_sample_spec(pa_sample_format.PA_SAMPLE_S16LE, 44100.toUInt, 2.toUByte) | |
| val pa_simple = pa_simple_new( | |
| null, | |
| c"ScalaNativeApp", | |
| pa_stream_direction.PA_STREAM_PLAYBACK, | |
| null, | |
| c"Music", | |
| spec, | |
| null, | |
| null, | |
| null | |
| ) | |
| val pcmBytes = readPcm() | |
| val rawSize = pcmBytes.length | |
| val buffer = makeNativeArray(pcmBytes) | |
| val err = (0 : CInt).toPtr[CInt] | |
| val result = pa_simple_write(pa_simple, buffer, rawSize.toUInt, err) | |
| if (result < 0) { | |
| println("error simple write") | |
| val code = !err | |
| println(s"error code: ${code}") | |
| } else { | |
| println("ok simple write") | |
| } | |
| pa_simple_free(pa_simple) | |
| println("Done.") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment