Skip to content

add convert stereo to mono function #96

Open
@trackme518

Description

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
	}

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions