DS Programming – Messing with basic sound

The second program I made was to test some basic sound functionality. I basically have the DS play a sinewave. The panning can be influenced by moving left or right on the touchscreen, the frequency by moving up or down. Hit the A button to toggle sound on/off. Using the L and R shoulder buttons you can change the dutycycle of the wave.

As always, here’s the code if you would like to give it a try:

#include <stdio.h>
#include <nds.h>
#include <nds/ndstypes.h>
int sound = 0;
int sndStatus = 0;
touchPosition TouchStructure;
u16 Pressed;
u16 Held;
u16 Released;
const int FREQ_MUL = 100;
const int VOLUME = 64;
int main(void) {
	int xPos = 120;
	int yPos = 40;
	int span = 64;
	int duty = 50;
	sound = soundPlayPSG(duty,yPos * FREQ_MUL,VOLUME,span);	
		Pressed = keysDown();
		Held = keysHeld();
		Released = keysUp();
		if(TouchStructure.px > 0)
			xPos = TouchStructure.px;
			span = div32(xPos, 2);
			soundSetPan(sound, span);
			iprintf("xPos: %d - pan: %d\n", xPos, span);
		if(TouchStructure.py > 0)
			yPos = TouchStructure.py;
			iprintf("yPos: %d\n", yPos);
		if(KEY_A & Pressed && sndStatus == 0)
			sndStatus = 1;
			iprintf("Sound On\n");
		else if(KEY_A & Pressed && sndStatus == 1)
			sndStatus = 0;
			iprintf("Sound OFF\n");
		soundSetFreq(sound, yPos * FREQ_MUL);
		if(KEY_L & Pressed)
			if(duty >= 5)
				duty -= 5;
		if(KEY_R & Pressed)
			if(duty <= 95)
				duty += 5;
		soundSetWaveDuty(sound, duty);
		if(KEY_B & Pressed)
			iprintf("Freq is %d, pan is %d, duty is%d\n", yPos, span, duty);		

Note that for the panning variable I used span, initially I used ‘pan’ but for some reason that didn’t work as pan was always 0 whatever I did with it. I also wasn’t really sure how to have the A button toggle the sound, I didn’t find a function that grabs the status whether the sound is on or off so I added my own variable to keep track of it.

Also notice my FREQ_MUL, as I did with the panning conversion, I added a multiplier since I’m using the y-values of the touching on the screen. Since the screen is only about 200 pixels in height it would be no fun to just have frequencies ranging from 1 to 200 Hz.

It’s really amazing how easy it is to make basic applications that work on the DS thanks to libnds and DevKitPRO. I wonder if it has surpassed the official Nintendo SDK in usefulness after all these years of improving it. It really is a sad thing all of these official SDKs aren’t available for the masses.

The next thing I’m going to give a try is something with graphics. NightFox’s graphics library seems to be quite nice for beginning developers. Thanks to the Grit application converting bitmap files into supported files that the NDS can display is a breeze.