RingDotNetfor Ring

Sound

A program can play a sound it makes itself. This lesson builds a WAV file from numbers (a Ring text can hold any byte), plays it with SoundPlayer, and shows what to do when a framework class has no Ring class yet - wrap it from the DLL of the framework.

What you will learn#

A class that has no Ring class#

The package wraps the namespaces that most programs use (System, System.IO, System.Windows.Forms and others; the class reference lists every class). SoundPlayer is in System.Media, which is not one of them. A class that is not listed has no Ring class, but it is in a DLL of the framework, and the generator that the package uses for your own libraries (A library written in C#) can wrap a namespace of any DLL:

Shell
ring wrapassembly.ring System.Windows.Extensions.dll classes System.Media

The last words name the namespaces to wrap (without them, every namespace of the DLL is wrapped). The program then does dnLoad and dnImportFrom as for any other library.

This DLL is in the folder of the desktop runtime, next to System.Windows.Forms.dll, and that folder is different on every computer. The program does not write a path: it asks a Windows Forms class where it lives, new Label().GetType().Assembly.Location, and takes the folder of that file.

Note

This lesson runs on Windows only, because SoundPlayer uses the sound system of Windows (the program says so on another system).

The program#

samples/UsingDotNet/tutorials/ch13_sound.ring
# sound - SoundPlayer is a framework class that has no Ring class in the package: wrapassembly.ring makes one from the DLL of the framework.
#   The sound is a WAV file made in memory from Ring numbers (a Ring text can hold any byte). Run it with --play to hear it.
load "dotnet.ring"

using {
	"System.IO"
	"System.Windows.Forms"
}

if not iswindows()
	? "SoundPlayer is a class of Windows, so this lesson runs on Windows only."
	bye
ok

cHere = currentdir()
cClasses = cHere + "/Sound/classes"

# STEP 1. Where is the DLL? SoundPlayer is in System.Windows.Extensions.dll, in the folder of the desktop runtime, where
# System.Windows.Forms.dll is too: the program asks a Windows Forms class for its folder instead of writing the path of one computer.
func main

	cFormsDll = new Label().GetType().Assembly.Location
	cFolder = new Path().GetDirectoryName(cFormsDll)
	cDll = new Path().Combine([cFolder,"System.Windows.Extensions.dll"])
	? "the DLL is next to System.Windows.Forms.dll: " + new File().Exists(cDll)

	# STEP 2. Make Ring classes for the namespace System.Media of that DLL, and load them
	chdir("../../../tools/dotnettools")
	system(exefilename() + ' wrapassembly.ring "' + cDll + '" "' + cClasses + '" System.Media > nul')
	chdir(cHere)
	dnLoad(cDll)
	dnImportFrom(cClasses + "/","System.Media")

	# STEP 3. A sound: a WAV file is a header and the samples. One second at 8000 samples a second would be 16000 bytes; a quarter of a
	# second of the note A (440 hertz) is enough.
	nRate = 8000
	nSamples = nRate / 4
	cData = ""
	for nSample = 0 to nSamples - 1
		nValue = floor(sin(2 * 3.14159265 * 440 * nSample / nRate) * 12000)
		if nValue < 0 nValue += 65536 ok               # a 16-bit sample below 0 is stored as 65536 minus its size
		cData += char(nValue % 256) + char(floor(nValue / 256))
	next
	cWav = "RIFF" + le32(36 + len(cData)) + "WAVE"
	cWav += "fmt " + le32(16) + le16(1) + le16(1) + le32(nRate) + le32(nRate * 2) + le16(2) + le16(16)          # PCM, one channel, 16 bits
	cWav += "data" + le32(len(cData)) + cData
	? "samples: " + nSamples + ", bytes of the file: " + len(cWav)

	# STEP 4. The bytes go to a MemoryStream, and the stream to a SoundPlayer
	oStream = new MemoryStream().@New([ :buffer = cWav ])          # the constructor is chosen by the name of its parameter
	oPlayer = new SoundPlayer().@New([ :stream = oStream ])
	oPlayer.@Load()
	? "the sound is loaded: " + oPlayer.IsLoadCompleted

	if find(sysargv,"--play") > 0
		? "playing..."
		oPlayer.PlaySync()
	else
		? "(run the program with --play to hear it)"
	ok

# a number as bytes, the lowest byte first (little endian)
func le16 nNumber

	return char(nNumber % 256) + char(floor(nNumber / 256) % 256)

func le32 nNumber

	return le16(nNumber % 65536) + le16(floor(nNumber / 65536))
Output
the DLL is next to System.Windows.Forms.dll: 1
samples: 2000, bytes of the file: 4044
the sound is loaded: 1
(run the program with --play to hear it)

The program is silent by default, so that it can run in a test. Run it with --play to hear a quarter of a second of the note A.

How it works#

A sound is a list of numbers#

A microphone measures the air pressure many times a second, and a speaker moves to follow the numbers. A sound that the program makes is a wave (here sin) that is measured at fixed moments:

sin(2 * pi * 440 * nSample / nRate) is the value of the wave at sample number nSample, between -1 and 1, and multiplying it by 12000 makes a whole number.

The WAV file#

A WAV file is a header of 44 bytes that says what follows, and then the samples:

BytesContentHere
4RIFF, the kind of file
4the size of the rest of the file36 + the size of the data
4WAVE
4fmt , the format block
4the size of the format block16
2the format: 1 is plain samples (PCM)1
2channels: 1 is mono1
4samples in a second8000
4bytes in a second8000 × 2
2bytes of one sample, for all channels2
2bits of a sample16
4data
4the size of the samples in bytes2 × the number of samples
…the samples

Every number in the header is stored little endian: the lowest byte first. le16 and le32 at the end of the program do that: char(n % 256) is the lowest byte, and floor(n / 256) is what is left for the next one. A 16-bit sample that is below zero is stored as 65536 minus its size (the two's complement), so the program adds 65536 to a negative value before it splits it into two bytes.

A Ring text holds any byte#

char(0) to char(255) make single bytes, and a Ring text can contain all of them, also the byte 0. So the whole file is one text, cWav, with 4044 bytes. A text that goes to a byte[] parameter becomes the same bytes (the tutorial Binary files and Core concepts).

The stream and the player#

MemoryStream has several constructors, so it is made with the name of the parameter that you want to pass: dnNew("System.IO.MemoryStream",[ :buffer = cWav ]). The class that the generator wrote for SoundPlayer is used the same way: new SoundPlayer().@New([ :stream = oStream ]). The tutorial The generic functions explains the named form.

Load is a keyword of Ring, so the method of .NET is @Load() (a name that is a keyword gets an @ at the start). It reads the stream and checks that it is a good WAV file: a mistake in the header makes it raise an exception, so the line the sound is loaded is a test of the header as well.

Playing#

MethodWhat it does
PlaySync()plays the sound and waits until it ends
Play()plays on another thread and returns at once
PlayLooping()plays again and again until Stop()
Stop()stops the sound

Sounds that the system itself plays (SystemSounds.Beep) are in the same namespace, and the wrapped class can play them: SystemSounds is a static class, so a call goes through an object of the class.

What you learned#

Exercises#

  1. Run the program with --play, then change the frequency to 880 (one octave higher) and 220 (one octave lower).
  2. Make the note one second long and fade it: multiply every sample by (nSamples - nSample) / nSamples.
  3. Play two notes one after the other by adding the samples of the second one to cData before the header is made.
  4. Write the sound to a file with new File().WriteAllBytes(cFile, cWav) (the tutorial Files and folders) and play the file by name: new SoundPlayer().@New([ :soundLocation = cFile ]).

Next#

Native DLLs

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.