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

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

/*
 * sndtomono.c
 *	Convert stereo to mono by averaging channels
 * 	or by extracting left or right channel.
 */
#import <stdio.h>
#import <sound/sound.h>

void main (int argc, char *argv[])
{
    int err, nchans, sampleCount;
    SNDSoundStruct *sndin;
    short *data;
    int startsamp=0;
    int chan = 3;
    char **argindex = argv;

    while (--argc && **(++argindex) == '-') {
	switch (*(++(argindex[0]))) {
	case 'l':		/* -left */
	    chan = 2;
	    fprintf(stderr,"Taking left channel\n");
	    break;
	case 'r':		/* -right */
	    chan = 1;
	    fprintf(stderr,"Taking right channel\n");
	    break;
	case 's':		/* -sum */
	    chan = 3;
	    fprintf(stderr,"Averaging left and right channels\n");
	    break;
	default:
	    fprintf(stderr,"%s: Unknown switch -%s\n", argv[0], *argindex);
	    exit(1);
	}
    }

    if (argc < 2) {
	fprintf(stderr,
		"%s - convert stereo to mono by averaging channels\n"
		"\tor by extracting left or right channel\n",argv[0]);
	fprintf(stderr, "Usage: %s [-l] [-r] stereosoundfile monosoundfile\n",
		argv[0]);
	exit(1);
    }

/*
 * Input sound file
 */
    err = SNDReadSoundfile(argindex[0], &sndin);
    if (err) {
	fprintf(stderr, "%s: Can\'t read soundfile: %s\n", argv[0], argindex[0]);
	exit(1);
    }
    nchans = sndin->channelCount;
    if (sndin->dataFormat != SND_FORMAT_LINEAR_16) {
	fprintf(stderr, "Soundfile must be 16 bit linear\n");
	exit(1);
    }
    if (sndin->channelCount != 2) {
	fprintf(stderr, "Soundfile must be stereo!\n");
	exit(1);
    }
    sampleCount = sndin->dataSize / (2*sizeof(short)); /* per channel */
    data = (short *) ((char *)sndin + sndin->dataLocation);
    SNDSwapSoundToHost(data, data, sampleCount, sndin->channelCount,
		       sndin->dataFormat);

    switch (chan) {
    case 1:
	for (startsamp = 0; startsamp < sampleCount; startsamp++)
	  data[startsamp] = data[2*startsamp+1];
	break;
    case 2:
	for (startsamp = 0; startsamp < sampleCount; startsamp++)
	  data[startsamp] = data[2*startsamp];
	break;
    case 3:			/* Average left and right channels */
	for (startsamp = 0; startsamp < sampleCount; startsamp++)
	  data[startsamp] = (data[2*startsamp] + data[2*startsamp+1])>>1;
	break;
    }

    sndin->channelCount = 1;
    sndin->dataSize /= 2;

    SNDSwapHostToSound(data, data, sampleCount, sndin->channelCount,
		       sndin->dataFormat);
    if (SNDWriteSoundfile(argindex[1], sndin)) {
      fprintf(stderr, "%s: could not write output file '%s'\n", argv[0],
	      argindex[1]);
      exit(1);			/* error exit */
    }
}



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