processing-sound icon indicating copy to clipboard operation
processing-sound copied to clipboard

add convert stereo to mono function

Open trackme518 opened this issue 2 years ago • 0 comments

Hi, I propose adding function to convert stereo sample to mono, code below. It can be placed inside AudioSample.java I think. It works for me from Processing sketch when called on SoundFile.

To keep only one channel and discard the other:

        //this will stop playback if it is playing already
	public stereoToMono(int whichChannel){ //whichChannel should be 0 for left and 1 for roght
		float[] newBuffer = new float[this.frames()];
		if(whichChannel>1){
			whichChannel = 1;
		}
		if(whichChannel<0){
			whichChannel = 0;
		}
		for (int i = 0; i < newBuffer.length; i++) {
			newBuffer[i] = this.read(i, whichChannel);//read only left channel
		}
		this.resize(newBuffer.length, false); //change to mono
		this.write(newBuffer); //copy data from single channel into buffer
	}

To sum up two channels into one:

        //this will stop playback if it is playing already
	public stereoToMono(int whichChannel){ //whichChannel should be 0 for left and 1 for roght
		float[] newBuffer = new float[this.frames()];
		if(whichChannel>1){
			whichChannel = 1;
		}
		if(whichChannel<0){
			whichChannel = 0;
		}
		for (int i = 0; i < newBuffer.length; i++) {
                        float left = bufferData[i] = sample.read(i, 0);
                        float right = bufferData[i] = sample.read(i, 1);			
                        newBuffer[i] = (left+right)/2;
		}
		this.resize(newBuffer.length, false); //change to mono
		this.write(newBuffer); //copy data from single channel into buffer
	}

trackme518 avatar Dec 24 '23 21:12 trackme518