ftp.nice.ch/pub/next/unix/audio/sndutil.1.3.s.tar.gz#/sndutil-1.3/sndtools/sndscale.c

This is sndscale.c in view mode; [Download] [Up]

/*
 * sndscale.c
 *	Apply scale factor to a sound
 */
#import <stdio.h>
#import <math.h>		/* pow() */
#import <sound/sound.h>

static int trace = 1;		/* for debugging */

static void fails(char *s, char *s2)
{
    printf("sndscale: ");	/* error message  */
    printf(s,s2);
    printf("\n\n");
    exit(1);			/* error exit */
}

void main (int argc, char *argv[])
{
    int err, nchans, sampleCount, chanSamples;
    SNDSoundStruct *sndin;
    FILE *outstream;
    short *data;
    double scaleFactor;
    int scaleTo = 0;

    if (argc > 1 && *argv[1] == '-') {
	scaleTo = 1;
	argv++;
	argc--;
    }

    if (argc != 4) {
	fprintf(stderr,"%s - apply scale factor to a sound\n",argv[0]);
	fprintf(stderr, "Usage: sndscale [-to] scalefactor in.snd out.snd\n");
	exit(1);
    }

/*
 * Scale factor
 */
    sscanf(argv[1],"%lf",&scaleFactor);

    printf("Scaling %s %s %f . . .\n",argv[2],(scaleTo?"to":"by"),scaleFactor);

/*
 * Input sound file
 */
    err = SNDReadSoundfile(argv[2], &sndin);
    if (err) {
	fprintf(stderr, "Cannot read soundfile: %s\n", argv[2]);
	exit(1);
    }
    nchans = sndin->channelCount;
    if (sndin->dataFormat != SND_FORMAT_LINEAR_16) {
	fprintf(stderr, "Soundfile must be 16 bit linear\n");
	exit(1);
    }
    sampleCount = sndin->dataSize / sizeof(short); /* channel independent */
    chanSamples = sampleCount / nchans;	/* channel dependent */
    data = (short *) ((char *)sndin + sndin->dataLocation);
    SNDSwapSoundToHost(data, data, chanSamples, nchans, sndin->dataFormat);
    {
      register short *sp;
      register int temp;
      register int scl;
      register int i;
      if (scaleTo) {
	  short amp,maxamp;
	  for (i = 0, sp=data, maxamp=0; i < sampleCount; i++) {
	      amp = abs(*sp++);
	      if (amp>maxamp) maxamp = amp;
	  }
	  scaleFactor = 32767.0 * scaleFactor / maxamp;
      }
      scl = scaleFactor * pow(2,16);
      for (i = 0, sp=data; i < sampleCount; i++) {
	  temp = *sp;
	  temp *= scl;
	  *sp++ = (temp >> 16);
      }	  
  }	  

/*
 * Output sound file
 */
    if (NULL == (outstream = fopen(argv[3],"w")))
      fails("could not open output file '%s'",argv[3]);
    if (SNDWriteHeader(fileno(outstream),sndin))
      fails("could not write output file '%s'",argv[3]);
    SNDSwapHostToSound(data, data, chanSamples, nchans, sndin->dataFormat);
    fwrite(data, sizeof(short), sampleCount, outstream);
    if (trace)
      printf("Wrote output file: %s\n",argv[3]);
}

These are the contents of the former NiCE NeXT User Group NeXTSTEP/OpenStep software archive, currently hosted by Netfuture.ch.