Create FLAC file using Kotlin and libsndfile in Windows

Submitted by Dickens A S on Mon, 07/05/2021 - 02:46

libsndfile is an industrial standard auto library and it is in C

Below is the code which is written in Kotlin multiplatform and cinterop 

Kotlin Code

fun main() {
   memScoped {
      
      info.channels = 1;
      info.samplerate = 22050;
      info.format = (SF_FORMAT_FLAC or SF_FORMAT_PCM_16).toInt();
      
      if (sf_format_check(info.ptr) == 0) {
        println("Invalid encoding\n");
        return;
      }
      
      var freq = 2000.0f;
      var seconds = 1;
      var sample_rate = 22050;
      var buf_size = seconds * sample_rate;
      var samples = ShortArray(buf_size)
      for (i in 0..buf_size-1) {
         samples[i] = (32760 * sin( (2.0f*PI*freq)/sample_rate * i )).toInt().toShort()
      }
      
      var outfilename = "abcd.flac"
      
      output = sf_open(outfilename, SFM_WRITE.toInt(), info.ptr);

      sf_write_short(output, samples.toCValues(), buf_size.toLong());

      sf_close(output);
      
   }
}

GitHub: https://github.com/dickensas/kotlin-gradle-templates/tree/master/sndfile-generate

A FLAC auto file named "abcd.flac" will be created inside "app" folder

you can open it using Windows Media Player or VLC or any other compatible player

Note: The output variable and info variable are declared inside the ".def" file as C variables

 

 

Add new comment