Digital Music Programming II: osc~

This lab demonstrates how to create an oscillator with minimal harmonic distortion.

Source Code Example Usage

#include "ext.h"
#include "z_dsp.h"

#ifndef TWOPI
   #define TWOPI 6.28318530718

typedef struct {
   t_pxobject msp_data;
   float      currentphase;
   float      phaseincrement;
} MyObject;

void* object_data;

void   main             (void);
void*  create_object    (void);
void   MessageDSP       (MyObject* mo, t_signal** signal, short* count);
void   InputFrequency   (MyObject* mo, float value);
void   InputPhase       (MyObject* mo, float value);
t_int* Perform          (t_int *parameters);
float  randfloat        (void);

void main(void) {
   setup((t_messlist**)&object_data, (method)create_object, (method)dsp_free,
         (short)sizeof(MyObject), NULL, A_NOTHING);
   addftx((method)InputPhase, 1);
   addmess((method)MessageDSP,   "dsp",   A_CANT, A_NOTHING);

void* create_object(void) {
   MyObject *mo = (MyObject*)newobject(object_data);
   dsp_setup((t_pxobject*)mo, 1);
   outlet_new((t_pxobject*)mo, "signal");
   floatin(mo, 1);
   InputPhase(mo, 0.0);
   InputFrequency(mo, 440.0);
   return mo;

void MessageDSP(MyObject* mo, t_signal** signal, short* count) {
   #pragma unused(mo)
   #pragma unused(count)
   dsp_add(Perform, 5, 5, mo, signal[0]->s_vec, signal[1]->s_vec, signal[0]->s_n);

void InputFrequency(MyObject *mo, float value) {
   static float factor = TWOPI / sys_getsr();
   mo->phaseincrement = value * factor;

void InputPhase(MyObject *mo, float value) {
   mo->currentphase = value;

t_int* Perform(t_int *parameters) {
   long      pcount = (long)     (parameters[1]);
   MyObject *mo     = (MyObject*)(parameters[2]);
   t_float  *input  = (t_float*) (parameters[3]);
   t_float  *output = (t_float*) (parameters[4]);
   long      count  = (int)      (parameters[5]);
   long      i;

   for (i=0; i<count; i++) {
      output[i] = cos(mo->currentphase);
      mo->currentphase += mo->phaseincrement;
   if (mo->currentphase > TWOPI) {
      mo->currentphase -= TWOPI;

   return parameters+pcount+1;


  1. Compile and test the osc~ object with the following patch: