Gary Sieling

How to Write a Wav File in Scala

The following code will play a chord to a Wav file using Scala. This is adapted from sample code and uses the library here to handle the file format.

One of the nice things about Scala is the ease of using existing Java code, since it runs on the JVM. I started this project by converting Java code into various functional languages, and ran into difficulties converting Java types into Clojure types, but have had no such problems with Scala.


object pitches {
	def write(filename: String) {
	    val G3 = 196;
	    val A3 = 220;
	    val F4G4 = 369.99
		
	    val notes = Array[Double]( G3, A3, F4G4 );
	    val file = new File(filename)
		
	    val sampleRate : Long = 44100; 
	    val duration : Double = 10.0;
	    val bufferSize : Int = 100;
	
	    val numFrames : Long = 
                (duration * sampleRate).toLong
	    val wavFile = 
	        WavFile.newWavFile(file, 1, numFrames, 
                                   16, sampleRate);
	    val buffer : Array[Array[Double]] = 
	        Array.fill(1, bufferSize)(0.0);
	
	    var frameCounter : Int = 0;
	
	    while (frameCounter < numFrames)
	    {
	        val remaining : Long = 
	        	   wavFile.getFramesRemaining();
	        val toWrite = 
	        	   if (remaining > bufferSize) 
	        	      bufferSize 
	        	   else 
                              remaining.toInt;
	
	        for (val s : Int 
	
Exit mobile version