processing / processing-sound

Audio library for Processing built with JSyn
https://processing.org/reference/libraries/sound/
GNU Lesser General Public License v2.1
149 stars 50 forks source link

add convert stereo to mono function #96

Open trackme518 opened 11 months ago

trackme518 commented 11 months ago

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
    }