Rendering a note as an audio file

This tutorial shows how a simple score can be rendered as an audio file. It produces a single note as a sine wave.

To hear the result below.

View / Download source

Lets have a closer look. 
import jm.music.data.*;
import jm.JMC;
import jm.audio.*;
import jm.util.*;
 
public class WaveformExample implements JMC {
	
	public static void main(String[] args) {
		new WaveformExample();
	}
	
	public WaveformExample() {
		// make a jMusic score
		Note n = new Note(C4, MINIM);
		Score score = new Score(new Part(new Phrase(n)));
		
		// set up an audio instrument
		Instrument sineWave = new SimpleSineInst(44100);
		
		// for jMusic 1.1 or earlier put the instrument in an array
		// Instrument[] ensemble = {sineWave};
 
		// render audio file of the score
		Write.au(score, "WaveformExample.au", sineWave);
		// for jMusic 1.1 or earlier substitute the line above with
		// Write.au(score, "WaveformExample.au", ensemble);
	}
}

The import statements at the head of the class feature the jm.audio.* package which provides access to the Instrument class. The jm.music.* package and jm.JMC class are used to create the score, and the jm.util.* package contains the Write class that handles the rendering of scores to audio (and MIDI by the way).

The declaration of a jMusic instrument or array of instruments is required to render the score as audio. For now we will focus on using existing instruments, in time you should aim to build your own instruments. There are a selection of instruments, including the ones used in these tutorials, availible from the jMusic web site if you don't already have them.

Instrument sineWave = new SimpleSineInst(44100);

This line declares an instance of the SimpleSineInst class, which we've called "sineWave" (for obvious reasons). The SimpleSineInst class takes one argument, the sample rate to be used. In this case 44100 samples per second; the same quality as CD audio.

In jMusic the rendering of a score as an audio file requires very similar code to writing MIDI files.

Write.au(score, "WaveformExample.au", sineWave);

This final line of code class the au method of the Write class for audio rendering of the score. The method takes three arguments, the score object, the name for the resulting file, and the instrument (or instrument array) to be used.

The score is created in the normal way (see other jMusic tutorials for details), and the file name can be any string but is typically one that ends in 'dot' au to indicate that the file is in that format. By default the Write.au() method will render a 16 bit file.


jMusic Tutorial Index

© 2001 Andrew Brown