code
stringlengths
11
173k
docstring
stringlengths
2
593k
func_name
stringlengths
2
189
language
stringclasses
1 value
repo
stringclasses
844 values
path
stringlengths
11
294
url
stringlengths
60
339
license
stringclasses
4 values
public void skip(double seconds){ bytesToSkip = Math.round(seconds * format.getSampleRate()) * format.getFrameSize(); }
Skip a number of seconds before processing the stream. @param seconds The number of seconds to skip
AudioDispatcher::skip
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public void setStepSizeAndOverlap(final int audioBufferSize, final int bufferOverlap){ audioFloatBuffer = new float[audioBufferSize]; floatOverlap = bufferOverlap; floatStepSize = audioFloatBuffer.length - floatOverlap; audioByteBuffer = new byte[audioFloatBuffer.length * format.getFrameSize()]; byteOverlap = floatOverlap * format.getFrameSize(); byteStepSize = floatStepSize * format.getFrameSize(); }
Set a new step size and overlap size. Both in number of samples. Watch out with this method: it should be called after a batch of samples is processed, not during. @param audioBufferSize The size of the buffer defines how much samples are processed in one step. Common values are 1024,2048. @param bufferOverlap How much consecutive buffers overlap (in samples). Half of the AudioBufferSize is common (512, 1024) for an FFT.
AudioDispatcher::setStepSizeAndOverlap
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public void setZeroPadFirstBuffer(boolean zeroPadFirstBuffer){ this.zeroPadFirstBuffer = zeroPadFirstBuffer; }
if zero pad is true then the first buffer is only filled up to buffer size - hop size E.g. if the buffer is 2048 and the hop size is 48 then you get 2000x0 and 48 filled audio samples @param zeroPadFirstBuffer true if the buffer should be zeroPadFirstBuffer, false otherwise.
AudioDispatcher::setZeroPadFirstBuffer
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public void setZeroPadLastBuffer(boolean zeroPadLastBuffer) { this.zeroPadLastBuffer = zeroPadLastBuffer; }
If zero pad last buffer is true then the last buffer is filled with zeros until the normal amount of elements are present in the buffer. Otherwise the buffer only contains the last elements and no zeros. By default it is set to true. @param zeroPadLastBuffer A boolean to control whether the last buffer is zero-padded.
AudioDispatcher::setZeroPadLastBuffer
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public void addAudioProcessor(final AudioProcessor audioProcessor) { audioProcessors.add(audioProcessor); LOG.fine("Added an audioprocessor to the list of processors: " + audioProcessor.toString()); }
Adds an AudioProcessor to the chain of processors. @param audioProcessor The AudioProcessor to add.
AudioDispatcher::addAudioProcessor
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public void removeAudioProcessor(final AudioProcessor audioProcessor) { audioProcessors.remove(audioProcessor); audioProcessor.processingFinished(); LOG.fine("Remove an audioprocessor to the list of processors: " + audioProcessor); }
Removes an AudioProcessor to the chain of processors and calls its <code>processingFinished</code> method. @param audioProcessor The AudioProcessor to remove.
AudioDispatcher::removeAudioProcessor
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public void stop() { stopped = true; for (final AudioProcessor processor : audioProcessors) { processor.processingFinished(); } try { audioInputStream.close(); } catch (IOException e) { LOG.log(Level.SEVERE, "Closing audio stream error.", e); } }
Stops dispatching audio data.
AudioDispatcher::stop
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
private int readNextAudioBlock() throws IOException { assert floatOverlap < audioFloatBuffer.length; // Is this the first buffer? boolean isFirstBuffer = (bytesProcessed ==0 || bytesProcessed == bytesToSkip); final int offsetInBytes; final int offsetInSamples; final int bytesToRead; //Determine the amount of bytes to read from the stream if(isFirstBuffer && !zeroPadFirstBuffer){ //If this is the first buffer and we do not want to zero pad the //first buffer then read a full buffer bytesToRead = audioByteBuffer.length; // With an offset in bytes of zero; offsetInBytes = 0; offsetInSamples=0; }else{ //In all other cases read the amount of bytes defined by the step size bytesToRead = byteStepSize; offsetInBytes = byteOverlap; offsetInSamples = floatOverlap; } //Shift the audio information using array copy since it is probably faster than manually shifting it. // No need to do this on the first buffer if(!isFirstBuffer && audioFloatBuffer.length == floatOverlap + floatStepSize ){ System.arraycopy(audioFloatBuffer,floatStepSize, audioFloatBuffer,0 ,floatOverlap); /* for(int i = floatStepSize ; i < floatStepSize+floatOverlap ; i++){ audioFloatBuffer[i-floatStepSize] = audioFloatBuffer[i]; }*/ } // Total amount of bytes read int totalBytesRead = 0; // The amount of bytes read from the stream during one iteration. int bytesRead=0; // Is the end of the stream reached? boolean endOfStream = false; // Always try to read the 'bytesToRead' amount of bytes. // unless the stream is closed (stopped is true) or no bytes could be read during one iteration while(!stopped && !endOfStream && totalBytesRead<bytesToRead){ try{ bytesRead = audioInputStream.read(audioByteBuffer, offsetInBytes + totalBytesRead , bytesToRead - totalBytesRead); }catch(IndexOutOfBoundsException e){ // The pipe decoder generates an out of bounds if end // of stream is reached. Ugly hack... bytesRead = -1; } if(bytesRead == -1){ // The end of the stream is reached if the number of bytes read during this iteration equals -1 endOfStream = true; }else{ // Otherwise add the number of bytes read to the total totalBytesRead += bytesRead; } } if(endOfStream){ // Could not read a full buffer from the stream, there are two options: if(zeroPadLastBuffer){ //Make sure the last buffer has the same length as all other buffers and pad with zeros for(int i = offsetInBytes + totalBytesRead; i < audioByteBuffer.length; i++){ audioByteBuffer[i] = 0; } converter.toFloatArray(audioByteBuffer, offsetInBytes, audioFloatBuffer, offsetInSamples, floatStepSize); }else{ // Send a smaller buffer through the chain. byte[] audioByteBufferContent = audioByteBuffer; audioByteBuffer = new byte[offsetInBytes + totalBytesRead]; System.arraycopy(audioByteBufferContent, 0, audioByteBuffer, 0, audioByteBuffer.length); int totalSamplesRead = totalBytesRead/format.getFrameSize(); audioFloatBuffer = new float[offsetInSamples + totalBytesRead/format.getFrameSize()]; converter.toFloatArray(audioByteBuffer, offsetInBytes, audioFloatBuffer, offsetInSamples, totalSamplesRead); } }else if(bytesToRead == totalBytesRead) { // The expected amount of bytes have been read from the stream. if(isFirstBuffer && !zeroPadFirstBuffer){ converter.toFloatArray(audioByteBuffer, 0, audioFloatBuffer, 0, audioFloatBuffer.length); }else{ converter.toFloatArray(audioByteBuffer, offsetInBytes, audioFloatBuffer, offsetInSamples, floatStepSize); } } else if(!stopped) { // If the end of the stream has not been reached and the number of bytes read is not the // expected amount of bytes, then we are in an invalid state; throw new IOException(String.format("The end of the audio stream has not been reached and the number of bytes read (%d) is not equal " + "to the expected amount of bytes(%d).", totalBytesRead,bytesToRead)); } // Makes sure AudioEvent contains correct info. audioEvent.setFloatBuffer(audioFloatBuffer); audioEvent.setOverlap(offsetInSamples); return totalBytesRead; }
Reads the next audio block. It tries to read the number of bytes defined by the audio buffer size minus the overlap. If the expected number of bytes could not be read either the end of the stream is reached or something went wrong. The behavior for the first and last buffer is defined by their corresponding the zero pad settings. The method also handles the case if the first buffer is also the last. @return The number of bytes read. @throws IOException When something goes wrong while reading the stream. In particular, an IOException is thrown if the input stream has been closed.
AudioDispatcher::readNextAudioBlock
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public TarsosDSPAudioFormat getFormat(){ return format; }
The current format used to convert floats to bytes and back. @return The current format used to convert floats to bytes and back.
AudioDispatcher::getFormat
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public float secondsProcessed(){ return bytesProcessed / (format.getSampleSizeInBits() / 8) / format.getSampleRate() / format.getChannels() ; }
@return The currently processed number of seconds.
AudioDispatcher::secondsProcessed
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public void setAudioFloatBuffer(float[] audioBuffer){ audioFloatBuffer = audioBuffer; }
Set a new audio buffer @param audioBuffer The audio buffer to use.
AudioDispatcher::setAudioFloatBuffer
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
public boolean isStopped(){ return stopped; }
@return True if the dispatcher is stopped or the end of stream has been reached.
AudioDispatcher::isStopped
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioDispatcher.java
Apache-2.0
private void calculateFrequencyEstimates() { for(int i = 0;i < frequencyEstimates.length;i++){ frequencyEstimates[i] = getFrequencyForBin(i); } }
For each bin, calculate a precise frequency estimate using phase offset.
SpectralPeakProcessor::calculateFrequencyEstimates
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
public float[] getMagnitudes() { return magnitudes.clone(); }
@return the magnitudes.
SpectralPeakProcessor::getMagnitudes
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
public float[] getFrequencyEstimates(){ return frequencyEstimates.clone(); }
@return the precise frequency for each bin.
SpectralPeakProcessor::getFrequencyEstimates
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
private float getFrequencyForBin(int binIndex){ final float frequencyInHertz; // use the phase delta information to get a more precise // frequency estimate // if the phase of the previous frame is available. // See // * Moore 1976 // "The use of phase vocoder in computer music applications" // * Sethares et al. 2009 - Spectral Tools for Dynamic // Tonality and Audio Morphing // * Laroche and Dolson 1999 if (previousPhaseOffsets != null) { float phaseDelta = currentPhaseOffsets[binIndex] - previousPhaseOffsets[binIndex]; long k = Math.round(cbin * binIndex - inv_2pi * phaseDelta); frequencyInHertz = (float) (inv_2pideltat * phaseDelta + inv_deltat * k); } else { frequencyInHertz = (float) fft.binToHz(binIndex, sampleRate); } return frequencyInHertz; }
Calculates a frequency for a bin using phase info, if available. @param binIndex The FFT bin index. @return a frequency, in Hz, calculated using available phase info.
SpectralPeakProcessor::getFrequencyForBin
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
public static float[] calculateNoiseFloor(float[] magnitudes, int medianFilterLength, float noiseFloorFactor) { double[] noiseFloorBuffer; float[] noisefloor = new float[magnitudes.length]; float median = (float) median(magnitudes.clone()); // Naive median filter implementation. // For each element take a median of surrounding values (noiseFloorBuffer) // Store the median as the noise floor. for (int i = 0; i < magnitudes.length; i++) { noiseFloorBuffer = new double[medianFilterLength]; int index = 0; for (int j = i - medianFilterLength/2; j <= i + medianFilterLength/2 && index < noiseFloorBuffer.length; j++) { if(j >= 0 && j < magnitudes.length){ noiseFloorBuffer[index] = magnitudes[j]; } else{ noiseFloorBuffer[index] = median; } index++; } // calculate the noise floor value. noisefloor[i] = median(noiseFloorBuffer) * (noiseFloorFactor); } float rampLength = 12.0f; for(int i = 0 ; i <= rampLength ; i++){ //ramp float ramp = 1.0f; ramp = (float) (-1 * (Math.log(i/rampLength))) + 1.0f; noisefloor[i] = ramp * noisefloor[i]; } return noisefloor; }
Calculate a noise floor for an array of magnitudes. @param magnitudes The magnitudes of the current frame. @param medianFilterLength The length of the median filter used to determine the noise floor. @param noiseFloorFactor The noise floor is multiplied with this factor to determine if the information is either noise or an interesting spectral peak. @return a float array representing the noise floor.
SpectralPeakProcessor::calculateNoiseFloor
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
public static List<Integer> findLocalMaxima(float[] magnitudes,float[] noisefloor){ List<Integer> localMaximaIndexes = new ArrayList<Integer>(); for (int i = 1; i < magnitudes.length - 1; i++) { boolean largerThanPrevious = (magnitudes[i - 1] < magnitudes[i]); boolean largerThanNext = (magnitudes[i] > magnitudes[i + 1]); boolean largerThanNoiseFloor = (magnitudes[i] > noisefloor[i]); if (largerThanPrevious && largerThanNext && largerThanNoiseFloor) { localMaximaIndexes.add(i); } } return localMaximaIndexes; }
Finds the local magintude maxima and stores them in the given list. @param magnitudes The magnitudes. @param noisefloor The noise floor. @return a list of local maxima.
SpectralPeakProcessor::findLocalMaxima
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
private static int findMaxMagnitudeIndex(float[] magnitudes){ int maxMagnitudeIndex = 0; float maxMagnitude = (float) -1e6; for (int i = 1; i < magnitudes.length - 1; i++) { if(magnitudes[i] > maxMagnitude){ maxMagnitude = magnitudes[i]; maxMagnitudeIndex = i; } } return maxMagnitudeIndex; }
@param magnitudes the magnitudes. @return the index for the maximum magnitude.
SpectralPeakProcessor::findMaxMagnitudeIndex
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
public static List<SpectralPeak> findPeaks(float[] magnitudes, float[] frequencyEstimates, List<Integer> localMaximaIndexes, int numberOfPeaks, int minDistanceInCents){ int maxMagnitudeIndex = findMaxMagnitudeIndex(magnitudes); List<SpectralPeak> spectralPeakList = new ArrayList<SpectralPeak>(); if(localMaximaIndexes.size()==0) return spectralPeakList; float referenceFrequency=0; //the frequency of the bin with the highest magnitude referenceFrequency = frequencyEstimates[maxMagnitudeIndex]; //remove frequency estimates below zero for(int i = 0 ; i < localMaximaIndexes.size() ; i++){ if(frequencyEstimates[localMaximaIndexes.get(i)] < 0 ){ localMaximaIndexes.remove(i); frequencyEstimates[localMaximaIndexes.get(i)]=1;//Hz i--; } } //filter the local maxima indexes, remove peaks that are too close to each other //assumes that localmaximaIndexes is sorted from lowest to higest index for(int i = 1 ; i < localMaximaIndexes.size() ; i++){ double centCurrent = PitchConverter.hertzToAbsoluteCent(frequencyEstimates[localMaximaIndexes.get(i)]); double centPrev = PitchConverter.hertzToAbsoluteCent(frequencyEstimates[localMaximaIndexes.get(i-1)]); double centDelta = centCurrent - centPrev; if(centDelta < minDistanceInCents ){ if(magnitudes[localMaximaIndexes.get(i)] > magnitudes[localMaximaIndexes.get(i-1)]){ localMaximaIndexes.remove(i-1); }else{ localMaximaIndexes.remove(i); } i--; } } // Retrieve the maximum values for the indexes float[] maxMagnitudes = new float[localMaximaIndexes.size()]; for(int i = 0 ; i < localMaximaIndexes.size() ; i++){ maxMagnitudes[i] = magnitudes[localMaximaIndexes.get(i)]; } // Sort the magnitudes in ascending order Arrays.sort(maxMagnitudes); // Find the threshold, the first value or somewhere in the array. float peakthresh = maxMagnitudes[0]; if (maxMagnitudes.length > numberOfPeaks) { peakthresh = maxMagnitudes[maxMagnitudes.length - numberOfPeaks]; } //store the peaks for(Integer i : localMaximaIndexes){ if(magnitudes[i]>= peakthresh){ final float frequencyInHertz= frequencyEstimates[i]; //ignore frequencies lower than 30Hz float binMagnitude = magnitudes[i]; SpectralPeak peak = new SpectralPeak(0,frequencyInHertz, binMagnitude, referenceFrequency,i); spectralPeakList.add(peak); } } return spectralPeakList; }
@param magnitudes the magnitudes.. @param frequencyEstimates The frequency estimates for each bin. @param localMaximaIndexes The indexes of the local maxima. @param numberOfPeaks The requested number of peaks. @param minDistanceInCents The minimum distance in cents between the peaks @return A list with spectral peaks.
SpectralPeakProcessor::findPeaks
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
public static final float percentile( double[] arr, double p ) { if (p < 0 || p > 1) throw new IllegalArgumentException("Percentile out of range."); // Sort the array in ascending order. Arrays.sort(arr); // Calculate the percentile. double t = p*(arr.length - 1); int i = (int)t; return (float) ((i + 1 - t)*arr[i] + (t - i)*arr[i + 1]); }
Returns the p-th percentile of values in an array. You can use this function to establish a threshold of acceptance. For example, you can decide to examine candidates who score above the 90th percentile (0.9). The elements of the input array are modified (sorted) by this method. @param arr An array of sample data values that define relative standing. The contents of the input array are sorted by this method. @param p The percentile value in the range 0..1, inclusive. @return The p-th percentile of values in an array. If p is not a multiple of 1/(n - 1), this method interpolates to determine the value at the p-th percentile.
SpectralPeakProcessor::percentile
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SpectralPeakProcessor.java
Apache-2.0
public GainProcessor(double newGain) { setGain(newGain); }
Create a new gain processor @param newGain the gain
GainProcessor::GainProcessor
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/GainProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/GainProcessor.java
Apache-2.0
public void setGain(double newGain) { this.gain = newGain; }
Set the gain applied to the next buffer. @param newGain The new gain.
GainProcessor::setGain
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/GainProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/GainProcessor.java
Apache-2.0
public AudioGenerator(final int audioBufferSize, final int bufferOverlap){ this(audioBufferSize,bufferOverlap,44100); }
Create a new generator. @param audioBufferSize The size of the buffer defines how much samples are processed in one step. Common values are 1024,2048. @param bufferOverlap How much consecutive buffers overlap (in samples). Half of the AudioBufferSize is common (512, 1024) for an FFT.
AudioGenerator::AudioGenerator
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
private TarsosDSPAudioFormat getTargetAudioFormat(int targetSampleRate) { TarsosDSPAudioFormat audioFormat = new TarsosDSPAudioFormat(TarsosDSPAudioFormat.Encoding.PCM_SIGNED, targetSampleRate, 2 * 8, 1, 2, targetSampleRate, ByteOrder.BIG_ENDIAN.equals(ByteOrder.nativeOrder())); return audioFormat; }
Constructs the target audio format. The audio format is one channel signed PCM of a given sample rate. @param targetSampleRate The sample rate to convert to. @return The audio format after conversion.
AudioGenerator::getTargetAudioFormat
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
public void setStepSizeAndOverlap(final int audioBufferSize, final int bufferOverlap){ audioFloatBuffer = new float[audioBufferSize]; floatOverlap = bufferOverlap; floatStepSize = audioFloatBuffer.length - floatOverlap; }
Set a new step size and overlap size. Both in number of samples. Watch out with this method: it should be called after a batch of samples is processed, not during. @param audioBufferSize The size of the buffer defines how much samples are processed in one step. Common values are 1024,2048. @param bufferOverlap How much consecutive buffers overlap (in samples). Half of the AudioBufferSize is common (512, 1024) for an FFT.
AudioGenerator::setStepSizeAndOverlap
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
public void addAudioProcessor(final AudioProcessor audioProcessor) { audioProcessors.add(audioProcessor); LOG.fine("Added an audioprocessor to the list of processors: " + audioProcessor.toString()); }
Adds an AudioProcessor to the chain of processors. @param audioProcessor The AudioProcessor to add.
AudioGenerator::addAudioProcessor
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
public void removeAudioProcessor(final AudioProcessor audioProcessor) { audioProcessors.remove(audioProcessor); audioProcessor.processingFinished(); LOG.fine("Remove an audioprocessor to the list of processors: " + audioProcessor); }
Removes an AudioProcessor to the chain of processors and calls processingFinished. @param audioProcessor The AudioProcessor to remove.
AudioGenerator::removeAudioProcessor
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
public void stop() { stopped = true; for (final AudioProcessor processor : audioProcessors) { processor.processingFinished(); } }
Stops dispatching audio data.
AudioGenerator::stop
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
private void generateNextAudioBlock() { assert floatOverlap < audioFloatBuffer.length; //Shift the audio information using array copy since it is probably faster than manually shifting it. // No need to do this on the first buffer if(audioFloatBuffer.length == floatOverlap + floatStepSize ){ System.arraycopy(audioFloatBuffer, floatStepSize, audioFloatBuffer,0 ,floatOverlap); } samplesProcessed += floatStepSize; }
Reads the next audio block. It tries to read the number of bytes defined by the audio buffer size minus the overlap. If the expected number of bytes could not be read either the end of the stream is reached or something went wrong. The behavior for the first and last buffer is defined by their corresponding the zero pad settings. The method also handles the case if the first buffer is also the last.
AudioGenerator::generateNextAudioBlock
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
public float secondsProcessed(){ return samplesProcessed / format.getSampleRate() / format.getChannels() ; }
@return The currently processed number of seconds.
AudioGenerator::secondsProcessed
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/AudioGenerator.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/AudioGenerator.java
Apache-2.0
public WaveformSimilarityBasedOverlapAdd(Parameters params){ setParameters(params); applyNewParameters(); }
Create a new instance based on algorithm parameters for a certain audio format. @param params The parameters for the algorithm.
WaveformSimilarityBasedOverlapAdd::WaveformSimilarityBasedOverlapAdd
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
Apache-2.0
private void overlap(final float[] output, int outputOffset, float[] input,int inputOffset){ for(int i = 0 ; i < overlapLength ; i++){ int itemp = overlapLength - i; output[i + outputOffset] = (input[i + inputOffset] * i + pMidBuffer[i] * itemp ) / overlapLength; } }
Overlaps the sample in output with the samples in input. @param output The output buffer. @param input The input buffer.
WaveformSimilarityBasedOverlapAdd::overlap
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
Apache-2.0
private int seekBestOverlapPosition(float[] inputBuffer, int postion) { int bestOffset; double bestCorrelation, currentCorrelation; int tempOffset; int comparePosition; // Slopes the amplitude of the 'midBuffer' samples precalcCorrReferenceMono(); bestCorrelation = -10; bestOffset = 0; // Scans for the best correlation value by testing each possible // position // over the permitted range. for (tempOffset = 0; tempOffset < seekLength; tempOffset++) { comparePosition = postion + tempOffset; // Calculates correlation value for the mixing position // corresponding // to 'tempOffset' currentCorrelation = calcCrossCorr(pRefMidBuffer, inputBuffer,comparePosition); // heuristic rule to slightly favor values close to mid of the // range double tmp = (double) (2 * tempOffset - seekLength) / seekLength; currentCorrelation = ((currentCorrelation + 0.1) * (1.0 - 0.25 * tmp * tmp)); // Checks for the highest correlation value if (currentCorrelation > bestCorrelation) { bestCorrelation = currentCorrelation; bestOffset = tempOffset; } } return bestOffset; }
Seeks for the optimal overlap-mixing position. The best position is determined as the position where the two overlapped sample sequences are 'most alike', in terms of the highest cross-correlation value over the overlapping period @param inputBuffer The input buffer @param postion The position where to start the seek operation, in the input buffer. @return The best position.
WaveformSimilarityBasedOverlapAdd::seekBestOverlapPosition
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
Apache-2.0
void precalcCorrReferenceMono() { for (int i = 0; i < overlapLength; i++){ float temp = i * (overlapLength - i); pRefMidBuffer[i] = pMidBuffer[i] * temp; } }
Slopes the amplitude of the 'midBuffer' samples so that cross correlation is faster to calculate. Why is this faster?
WaveformSimilarityBasedOverlapAdd::precalcCorrReferenceMono
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
Apache-2.0
public Parameters(double tempo, double sampleRate, int newSequenceMs, int newSeekWindowMs, int newOverlapMs) { this.tempo = tempo; this.sampleRate = sampleRate; this.overlapMs = newOverlapMs; this.seekWindowMs = newSeekWindowMs; this.sequenceMs = newSequenceMs; }
@param tempo The tempo change 1.0 means unchanged, 2.0 is + 100% , 0.5 is half of the speed. @param sampleRate The sample rate of the audio 44.1kHz is common. @param newSequenceMs Length of a single processing sequence, in milliseconds. This determines to how long sequences the original sound is chopped in the time-stretch algorithm. The larger this value is, the lesser sequences are used in processing. In principle a bigger value sounds better when slowing down tempo, but worse when increasing tempo and vice versa. Increasing this value reduces computational burden and vice versa. @param newSeekWindowMs Seeking window length in milliseconds for algorithm that finds the best possible overlapping location. This determines from how wide window the algorithm may look for an optimal joining location when mixing the sound sequences back together. The bigger this window setting is, the higher the possibility to find a better mixing position will become, but at the same time large values may cause a "drifting" artifact because consequent sequences will be taken at more uneven intervals. If there's a disturbing artifact that sounds as if a constant frequency was drifting around, try reducing this setting. Increasing this value increases computational burden and vice versa. @param newOverlapMs Overlap length in milliseconds. When the chopped sound sequences are mixed back together, to form a continuous sound stream, this parameter defines over how long period the two consecutive sequences are let to overlap each other. This shouldn't be that critical parameter. If you reduce the DEFAULT_SEQUENCE_MS setting by a large amount, you might wish to try a smaller value on this. Increasing this value increases computational burden and vice versa.
Parameters::Parameters
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/WaveformSimilarityBasedOverlapAdd.java
Apache-2.0
public FadeIn(double d) // { this.duration=d; }
A new fade in processor @param d duration of the fade in seconds
FadeIn::FadeIn
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/FadeIn.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/FadeIn.java
Apache-2.0
public void stopFadeIn() { this.fadingIn=false; }
Stop fade in processing immediately
FadeIn::stopFadeIn
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/FadeIn.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/FadeIn.java
Apache-2.0
public void setBitDepth(int newBitDepth){ this.bitDepth = newBitDepth; }
Set a new bit depth @param newBitDepth The new bit depth.
BitDepthProcessor::setBitDepth
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/BitDepthProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/BitDepthProcessor.java
Apache-2.0
public int getBitDepth(){ return this.bitDepth; }
The current bit depth @return returns the current bit depth.
BitDepthProcessor::getBitDepth
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/BitDepthProcessor.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/BitDepthProcessor.java
Apache-2.0
public FadeOut(double d) // d= { this.duration=d; }
A new fade out processor @param d duration of the fade out in seconds
FadeOut::FadeOut
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/FadeOut.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/FadeOut.java
Apache-2.0
public void startFadeOut() { this.isFadeOut=true; }
Start fade out processing now
FadeOut::startFadeOut
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/FadeOut.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/FadeOut.java
Apache-2.0
public EnvelopeFollower(double sampleRate){ this(sampleRate,DEFAULT_ATTACK_TIME,DEFAULT_RELEASE_TIME); }
Create a new envelope follower, with a certain sample rate. @param sampleRate The sample rate of the audio signal.
EnvelopeFollower::EnvelopeFollower
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/EnvelopeFollower.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/EnvelopeFollower.java
Apache-2.0
public EnvelopeFollower(double sampleRate, double attackTime,double releaseTime){ gainAttack = (float) Math.exp(-1.0/(sampleRate*attackTime)); gainRelease = (float) Math.exp(-1.0/(sampleRate*releaseTime)); }
Create a new envelope follower, with a certain sample rate. @param sampleRate The sample rate of the audio signal. @param attackTime Defines how fast the envelope raises, defined in seconds. @param releaseTime Defines how fast the envelope goes down, defined in seconds.
EnvelopeFollower::EnvelopeFollower
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/EnvelopeFollower.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/EnvelopeFollower.java
Apache-2.0
public void calculateEnvelope(float[] buffer){ for(int i = 0 ; i < buffer.length ; i++){ float envelopeIn = Math.abs(buffer[i]); if(envelopeOut < envelopeIn){ envelopeOut = envelopeIn + gainAttack * (envelopeOut - envelopeIn); } else { envelopeOut = envelopeIn + gainRelease * (envelopeOut - envelopeIn); } buffer[i] = envelopeOut; } }
Determine the envelope of an audio buffer @param buffer The audio buffer.
EnvelopeFollower::calculateEnvelope
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/EnvelopeFollower.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/EnvelopeFollower.java
Apache-2.0
public ConstantQ(float sampleRate, float minFreq, float maxFreq,float binsPerOctave) { this(sampleRate,minFreq,maxFreq,binsPerOctave,0.001f,1.0f); }
Create a new ConstantQ instance @param sampleRate The audio sample rate @param minFreq The minimum frequency to report in Hz @param maxFreq The maximum frequency to report in Hz @param binsPerOctave The number of bins per octave
ConstantQ::ConstantQ
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public ConstantQ(float sampleRate, float minFreq, float maxFreq,float binsPerOctave, float threshold,float spread) { this.minimumFrequency = minFreq; this.maximumFreqency = maxFreq; this.binsPerOctave = (int) binsPerOctave; // Calculate Constant Q double q = 1.0 / (Math.pow(2, 1.0 / binsPerOctave) - 1.0) / spread; // Calculate number of output bins int numberOfBins = (int) Math.ceil(binsPerOctave * Math.log(maximumFreqency / minimumFrequency) / Math.log(2)); // Initialize the coefficients array (complex number so 2 x number of bins) coefficients = new float[numberOfBins*2]; // Initialize the magnitudes array magnitudes = new float[numberOfBins]; // Calculate the minimum length of the FFT to support the minimum // frequency float calc_fftlen = (float) Math.ceil(q * sampleRate / minimumFrequency); // No need to use power of 2 FFT length. fftLength = (int) calc_fftlen; //System.out.println(fftLength); //The FFT length needs to be a power of two for performance reasons: fftLength = (int) Math.pow(2, Math.ceil(Math.log(calc_fftlen) / Math.log(2))); // Create FFT object fft = new FFT(fftLength); qKernel = new float[numberOfBins][]; qKernel_indexes = new int[numberOfBins][]; frequencies = new float[numberOfBins]; // Calculate Constant Q kernels float[] temp = new float[fftLength*2]; float[] ctemp = new float[fftLength*2]; int[] cindexes = new int[fftLength]; for (int i = 0; i < numberOfBins; i++) { float[] sKernel = temp; // Calculate the frequency of current bin frequencies[i] = (float) (minimumFrequency * Math.pow(2, i/binsPerOctave )); // Calculate length of window int len = (int)Math.min(Math.ceil( q * sampleRate / frequencies[i]), fftLength); for (int j = 0; j < len; j++) { double window = -.5*Math.cos(2.*Math.PI*(double)j/(double)len)+.5;// Hanning Window // double window = -.46*Math.cos(2.*Math.PI*(double)j/(double)len)+.54; // Hamming Window window /= len; // Calculate kernel double x = 2*Math.PI * q * (double)j/(double)len; sKernel[j*2] = (float) (window * Math.cos(x)); sKernel[j*2+1] = (float) (window * Math.sin(x)); } for (int j = len*2; j < fftLength*2; j++) { sKernel[j] = 0; } // Perform FFT on kernel fft.complexForwardTransform(sKernel); // Remove all zeros from kernel to improve performance float[] cKernel = ctemp; int k = 0; for (int j = 0, j2 = sKernel.length - 2; j < sKernel.length/2; j+=2,j2-=2) { double absval = Math.sqrt(sKernel[j]*sKernel[j] + sKernel[j+1]*sKernel[j+1]); absval += Math.sqrt(sKernel[j2]*sKernel[j2] + sKernel[j2+1]*sKernel[j2+1]); if(absval > threshold) { cindexes[k] = j; cKernel[2*k] = sKernel[j] + sKernel[j2]; cKernel[2*k + 1] = sKernel[j + 1] + sKernel[j2 + 1]; k++; } } sKernel = new float[k * 2]; int[] indexes = new int[k]; if (k * 2 >= 0) System.arraycopy(cKernel, 0, sKernel, 0, k * 2); System.arraycopy(cindexes, 0, indexes, 0, k); // Normalize fft output for (int j = 0; j < sKernel.length; j++) sKernel[j] /= fftLength; // Perform complex conjugate on sKernel for (int j = 1; j < sKernel.length; j += 2) sKernel[j] = -sKernel[j]; for (int j = 0; j < sKernel.length; j ++) sKernel[j] = -sKernel[j]; qKernel_indexes[i] = indexes; qKernel[i] = sKernel; } }
Create a new ConstantQ instance @param sampleRate The audio sample rate @param minFreq The minimum frequency to report in Hz @param maxFreq The maximum frequency to report in Hz @param binsPerOctave The number of bins per octave @param threshold The threshold used in kernel construction. @param spread the spread used to calculate the Constant Q
ConstantQ::ConstantQ
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public void calculate(float[] inputBuffer) { fft.forwardTransform(inputBuffer); for (int i = 0; i < qKernel.length; i++) { float[] kernel = qKernel[i]; int[] indexes = qKernel_indexes[i]; float t_r = 0; float t_i = 0; for (int j = 0, l = 0; j < kernel.length; j += 2, l++) { int jj = indexes[l]; float b_r = inputBuffer[jj]; float b_i = inputBuffer[jj + 1]; float k_r = kernel[j]; float k_i = kernel[j + 1]; // COMPLEX: T += B * K t_r += b_r * k_r - b_i * k_i; t_i += b_r * k_i + b_i * k_r; } coefficients[i * 2] = t_r; coefficients[i * 2 + 1] = t_i; } }
Take an input buffer with audio and calculate the constant Q coefficients. @param inputBuffer The input buffer with audio.
ConstantQ::calculate
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public void calculateMagintudes(float[] inputBuffer) { calculate(inputBuffer); for(int i = 0 ; i < magnitudes.length ; i++){ magnitudes[i] = (float) Math.sqrt(coefficients[i*2] * coefficients[i*2] + coefficients[i*2+1] * coefficients[i*2+1]); } }
Take an input buffer with audio and calculate the constant Q magnitudes. @param inputBuffer The input buffer with audio.
ConstantQ::calculateMagintudes
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public float[] getFreqencies() { return frequencies; }
@return The list of starting frequencies for each band. In Hertz.
ConstantQ::getFreqencies
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public float[] getMagnitudes() { return magnitudes; }
Returns the Constant Q magnitudes calculated for the previous audio buffer. Beware: the array is reused for performance reasons. If your need to cache your results, please copy the array. @return The output buffer with constant q magnitudes. If you for example are interested in coefficients between 256 and 1024 Hz (2^8 and 2^10 Hz) and you requested 12 bins per octave, you will need 12 bins/octave * 2 octaves = 24 places in the output buffer.
ConstantQ::getMagnitudes
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public float[] getCoefficients() { return coefficients; }
Return the Constant Q coefficients calculated for the previous audio buffer. Beware: the array is reused for performance reasons. If your need to cache your results, please copy the array. @return The array with constant q coefficients. If you for example are interested in coefficients between 256 and 1024 Hz (2^8 and 2^10 Hz) and you requested 12 bins per octave, you will need 12 bins/octave * 2 octaves * 2 entries/bin = 48 places in the output buffer. The coefficient needs two entries in the output buffer since they are complex numbers.
ConstantQ::getCoefficients
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public int getNumberOfOutputBands() { return frequencies.length; }
@return The number of coefficients, output bands.
ConstantQ::getNumberOfOutputBands
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public int getFFTlength() { return fftLength; }
@return The required length the FFT.
ConstantQ::getFFTlength
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public int getBinsPerOctave(){ return binsPerOctave; }
@return the number of bins every octave.
ConstantQ::getBinsPerOctave
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/ConstantQ.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/ConstantQ.java
Apache-2.0
public SilenceDetector(){ this(DEFAULT_SILENCE_THRESHOLD,false); }
Create a new silence detector with a default threshold.
SilenceDetector::SilenceDetector
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SilenceDetector.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SilenceDetector.java
Apache-2.0
public SilenceDetector(final double silenceThreshold,boolean breakProcessingQueueOnSilence){ this.threshold = silenceThreshold; this.breakProcessingQueueOnSilence = breakProcessingQueueOnSilence; }
Create a new silence detector with a defined threshold. @param silenceThreshold The threshold which defines when a buffer is silent (in dB). Normal values are [-70.0,-30.0] dB SPL. @param breakProcessingQueueOnSilence
SilenceDetector::SilenceDetector
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SilenceDetector.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SilenceDetector.java
Apache-2.0
public static double calculateRMS(float[] floatBuffer){ double rms = 0.0; for (int i = 0; i < floatBuffer.length; i++) { rms += floatBuffer[i] * floatBuffer[i]; } rms = rms / Double.valueOf(floatBuffer.length); rms = Math.sqrt(rms); return rms; }
Calculates and returns the root mean square of the signal. Please cache the result since it is calculated every time. @param floatBuffer The audio buffer to calculate the RMS for. @return The <a href="http://en.wikipedia.org/wiki/Root_mean_square">RMS</a> of the signal present in the current buffer.
SilenceDetector::calculateRMS
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SilenceDetector.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SilenceDetector.java
Apache-2.0
private static double soundPressureLevel(final float[] buffer) { double rms = calculateRMS(buffer); return linearToDecibel(rms); }
Returns the dBSPL for a buffer. @param buffer The buffer with audio information. @return The dBSPL level for the buffer.
SilenceDetector::soundPressureLevel
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SilenceDetector.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SilenceDetector.java
Apache-2.0
private static double linearToDecibel(final double value) { return 20.0 * Math.log10(value); }
Converts a linear to a dB value. @param value The value to convert. @return The converted value.
SilenceDetector::linearToDecibel
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SilenceDetector.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SilenceDetector.java
Apache-2.0
public boolean isSilence(final float[] buffer, final double silenceThreshold) { currentSPL = soundPressureLevel(buffer); return currentSPL < silenceThreshold; }
Checks if the dBSPL level in the buffer falls below a certain threshold. @param buffer The buffer with audio information. @param silenceThreshold The threshold in dBSPL @return True if the audio information in buffer corresponds with silence, false otherwise.
SilenceDetector::isSilence
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/SilenceDetector.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/SilenceDetector.java
Apache-2.0
public float[] magnitudeSpectrum(float[] frame){ float[] magSpectrum = new float[frame.length]; // calculate FFT for current frame fft.forwardTransform(frame); // calculate magnitude spectrum for (int k = 0; k < frame.length/2; k++){ magSpectrum[frame.length/2+k] = fft.modulus(frame, frame.length/2-1-k); magSpectrum[frame.length/2-1-k] = magSpectrum[frame.length/2+k]; } return magSpectrum; }
computes the magnitude spectrum of the input frame<br> calls: none<br> called by: featureExtraction @param frame Input frame signal @return Magnitude Spectrum array
MFCC::magnitudeSpectrum
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
Apache-2.0
public float[] nonLinearTransformation(float[] fbank){ float[] f = new float[fbank.length]; final float FLOOR = -50; for (int i = 0; i < fbank.length; i++){ f[i] = (float) Math.log(fbank[i]); // check if ln() returns a value less than the floor if (f[i] < FLOOR) f[i] = FLOOR; } return f; }
the output of mel filtering is subjected to a logarithm function (natural logarithm)<br> calls: none<br> called by: featureExtraction @param fbank Output of mel filtering @return Natural log of the output of mel filtering
MFCC::nonLinearTransformation
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
Apache-2.0
public float[] melFilter(float[] bin, int[] centerFrequencies) { float[] temp = new float[amountOfMelFilters + 2]; for (int k = 1; k <= amountOfMelFilters; k++) { float num1 = 0, num2 = 0; float den = (centerFrequencies[k] - centerFrequencies[k - 1] + 1); for (int i = centerFrequencies[k - 1]; i <= centerFrequencies[k]; i++) { num1 += bin[i] * (i - centerFrequencies[k - 1] + 1); } num1 /= den; den = (centerFrequencies[k + 1] - centerFrequencies[k] + 1); for (int i = centerFrequencies[k] + 1; i <= centerFrequencies[k + 1]; i++) { num2 += bin[i] * (1 - ((i - centerFrequencies[k]) / den)); } temp[k] = num1 + num2; } float[] fbank = new float[amountOfMelFilters]; System.arraycopy(temp, 1, fbank, 0, amountOfMelFilters); return fbank; }
Calculate the output of the mel filter<br> calls: none called by: featureExtraction @param bin The bins. @param centerFrequencies The frequency centers. @return Output of mel filter.
MFCC::melFilter
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
Apache-2.0
public float[] cepCoefficients(float[] f){ float[] cepc = new float[amountOfCepstrumCoef]; for (int i = 0; i < cepc.length; i++){ for (int j = 0; j < f.length; j++){ cepc[i] += f[j] * Math.cos(Math.PI * i / f.length * (j + 0.5)); } } return cepc; }
Cepstral coefficients are calculated from the output of the Non-linear Transformation method<br> calls: none<br> called by: featureExtraction @param f Output of the Non-linear Transformation method @return Cepstral Coefficients
MFCC::cepCoefficients
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
Apache-2.0
protected static float freqToMel(float freq){ return 2595 * log10(1 + freq / 700); }
convert frequency to mel-frequency<br> calls: none<br> called by: featureExtraction @param freq Frequency @return Mel-Frequency
MFCC::freqToMel
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
Apache-2.0
private static float inverseMel(double x) { return (float) (700 * (Math.pow(10, x / 2595) - 1)); }
calculates the inverse of Mel Frequency<br> calls: none<br> called by: featureExtraction
MFCC::inverseMel
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
Apache-2.0
protected static float log10(float value){ return (float) (Math.log(value) / Math.log(10)); }
calculates logarithm with base 10<br> calls: none<br> called by: featureExtraction @param value Number to take the log of @return base 10 logarithm of the input values
MFCC::log10
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/mfcc/MFCC.java
Apache-2.0
public static float lrsFilterUp(float[] Imp, float[] ImpD, int Nwing, boolean Interp, float[] Xp_array, int Xp_index, double Ph, int Inc) { double a = 0; float v, t; Ph *= Resampler.Npc; // Npc is number of values per 1/delta in impulse // response v = 0.0f; // The output value float[] Hp_array = Imp; int Hp_index = (int) Ph; int End_index = Nwing; float[] Hdp_array = ImpD; int Hdp_index = (int) Ph; if (Interp) { // Hdp = &ImpD[(int)Ph]; a = Ph - Math.floor(Ph); /* fractional part of Phase */ } if (Inc == 1) // If doing right wing... { // ...drop extra coeff, so when Ph is End_index--; // 0.5, we don't do too many mult's if (Ph == 0) // If the phase is zero... { // ...then we've already skipped the Hp_index += Resampler.Npc; // first sample, so we must also Hdp_index += Resampler.Npc; // skip ahead in Imp[] and ImpD[] } } if (Interp) while (Hp_index < End_index) { t = Hp_array[Hp_index]; /* Get filter coeff */ t += Hdp_array[Hdp_index] * a; /* t is now interp'd filter coeff */ Hdp_index += Resampler.Npc; /* Filter coeff differences step */ t *= Xp_array[Xp_index]; /* Mult coeff by input sample */ v += t; /* The filter output */ Hp_index += Resampler.Npc; /* Filter coeff step */ Xp_index += Inc; /* Input signal step. NO CHECK ON BOUNDS */ } else while (Hp_index < End_index) { t = Hp_array[Hp_index]; /* Get filter coeff */ t *= Xp_array[Xp_index]; /* Mult coeff by input sample */ v += t; /* The filter output */ Hp_index += Resampler.Npc; /* Filter coeff step */ Xp_index += Inc; /* Input signal step. NO CHECK ON BOUNDS */ } return v; }
@param Imp impulse response @param ImpD impulse response deltas @param Nwing length of one wing of filter @param Interp Interpolate coefs using deltas? @param Xp_array Current sample array @param Xp_index Current sample index @param Ph Phase @param Inc increment (1 for right wing or -1 for left) @return v.
FilterKit::lrsFilterUp
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/FilterKit.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/FilterKit.java
Apache-2.0
public static float lrsFilterUD(float[] Imp, float[] ImpD, int Nwing, boolean Interp, float[] Xp_array, int Xp_index, double Ph, int Inc, double dhb) { float a; float v, t; double Ho; v = 0.0f; // The output value Ho = Ph * dhb; int End_index = Nwing; if (Inc == 1) // If doing right wing... { // ...drop extra coeff, so when Ph is End_index--; // 0.5, we don't do too many mult's if (Ph == 0) // If the phase is zero... Ho += dhb; // ...then we've already skipped the } // first sample, so we must also // skip ahead in Imp[] and ImpD[] float[] Hp_array = Imp; int Hp_index; if (Interp) { float[] Hdp_array = ImpD; int Hdp_index; while ((Hp_index = (int) Ho) < End_index) { t = Hp_array[Hp_index]; // Get IR sample Hdp_index = (int) Ho; // get interp bits from diff table a = (float) (Ho - Math.floor(Ho)); // a is logically between 0 // and 1 t += Hdp_array[Hdp_index] * a; // t is now interp'd filter coeff t *= Xp_array[Xp_index]; // Mult coeff by input sample v += t; // The filter output Ho += dhb; // IR step Xp_index += Inc; // Input signal step. NO CHECK ON BOUNDS } } else { while ((Hp_index = (int) Ho) < End_index) { t = Hp_array[Hp_index]; // Get IR sample t *= Xp_array[Xp_index]; // Mult coeff by input sample v += t; // The filter output Ho += dhb; // IR step Xp_index += Inc; // Input signal step. NO CHECK ON BOUNDS } } return v; }
@param Imp impulse response @param ImpD impulse response deltas @param Nwing length of one wing of filter @param Interp Interpolate coefs using deltas? @param Xp_array Current sample array @param Xp_index Current sample index @param Ph Phase @param Inc increment (1 for right wing or -1 for left) @param dhb filter sampling period @return v.
FilterKit::lrsFilterUD
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/FilterKit.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/FilterKit.java
Apache-2.0
public RateTransposer(double factor){ this.factor = factor; r= new Resampler(false,0.1,4.0); }
Create a new sample rate transposer. The factor determines the new sample rate. E.g. 0.5 is half the sample rate, 1.0 does not change a thing and 2.0 doubles the samplerate. If the samples are played at the original speed the pitch doubles (0.5), does not change (1.0) or halves (0.5) respectively. Playback length follows the same rules, obviously. @param factor Determines the new sample rate. E.g. 0.5 is half the sample rate, 1.0 does not change a thing and 2.0 doubles the sample rate. If the samples are played at the original speed the pitch doubles (0.5), does not change (1.0) or halves (0.5) respectively. Playback length follows the same rules, obviously.
RateTransposer::RateTransposer
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/RateTransposer.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/RateTransposer.java
Apache-2.0
public Resampler(Resampler other) { this.Imp = other.Imp.clone(); this.ImpD = other.ImpD.clone(); this.LpScl = other.LpScl; this.Nmult = other.Nmult; this.Nwing = other.Nwing; this.minFactor = other.minFactor; this.maxFactor = other.maxFactor; this.XSize = other.XSize; this.X = other.X.clone(); this.Xp = other.Xp; this.Xread = other.Xread; this.Xoff = other.Xoff; this.Y = other.Y.clone(); this.Yp = other.Yp; this.Time = other.Time; }
Clone an existing resampling session. Faster than creating one from scratch. @param other
Result::Resampler
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/Resampler.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/Resampler.java
Apache-2.0
public Resampler(boolean highQuality, double minFactor, double maxFactor) { if (minFactor <= 0.0 || maxFactor <= 0.0) { throw new IllegalArgumentException("minFactor and maxFactor must be positive"); } if (maxFactor < minFactor) { throw new IllegalArgumentException("minFactor must be <= maxFactor"); } this.minFactor = minFactor; this.maxFactor = maxFactor; this.Nmult = highQuality ? 35 : 11; this.LpScl = 1.0f; this.Nwing = Npc * (this.Nmult - 1) / 2; // # of filter coeffs in right wing double Rolloff = 0.90; double Beta = 6; double[] Imp64 = new double[this.Nwing]; FilterKit.lrsLpFilter(Imp64, this.Nwing, 0.5 * Rolloff, Beta, Npc); this.Imp = new float[this.Nwing]; this.ImpD = new float[this.Nwing]; for (int i = 0; i < this.Nwing; i++) { this.Imp[i] = (float) Imp64[i]; } // Storing deltas in ImpD makes linear interpolation // of the filter coefficients faster for (int i = 0; i < this.Nwing - 1; i++) { this.ImpD[i] = this.Imp[i + 1] - this.Imp[i]; } // Last coeff. not interpolated this.ImpD[this.Nwing - 1] = -this.Imp[this.Nwing - 1]; // Calc reach of LP filter wing (plus some creeping room) int Xoff_min = (int) (((this.Nmult + 1) / 2.0) * Math.max(1.0, 1.0 / minFactor) + 10); int Xoff_max = (int) (((this.Nmult + 1) / 2.0) * Math.max(1.0, 1.0 / maxFactor) + 10); this.Xoff = Math.max(Xoff_min, Xoff_max); // Make the inBuffer size at least 4096, but larger if necessary // in order to store the minimum reach of the LP filter and then some. // Then allocate the buffer an extra Xoff larger so that // we can zero-pad up to Xoff zeros at the end when we reach the // end of the input samples. this.XSize = Math.max(2 * this.Xoff + 10, 4096); this.X = new float[this.XSize + this.Xoff]; this.Xp = this.Xoff; this.Xread = this.Xoff; // Make the outBuffer long enough to hold the entire processed // output of one inBuffer int YSize = (int) (((double) this.XSize) * maxFactor + 2.0); this.Y = new float[YSize]; this.Yp = 0; this.Time = this.Xoff; // Current-time pointer for converter }
Create a new resampling session. @param highQuality true for better quality, slower processing time @param minFactor lower bound on resampling factor for this session @param maxFactor upper bound on resampling factor for this session @throws IllegalArgumentException if minFactor or maxFactor is not positive, or if maxFactor is less than minFactor
Result::Resampler
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/Resampler.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/Resampler.java
Apache-2.0
public boolean process(double factor, SampleBuffers buffers, boolean lastBatch) { if (factor < this.minFactor || factor > this.maxFactor) { throw new IllegalArgumentException("factor " + factor + " is not between minFactor=" + minFactor + " and maxFactor=" + maxFactor); } int outBufferLen = buffers.getOutputBufferLength(); int inBufferLen = buffers.getInputBufferLength(); float[] Imp = this.Imp; float[] ImpD = this.ImpD; float LpScl = this.LpScl; int Nwing = this.Nwing; boolean interpFilt = false; // TRUE means interpolate filter coeffs int inBufferUsed = 0; int outSampleCount = 0; // Start by copying any samples still in the Y buffer to the output // buffer if ((this.Yp != 0) && (outBufferLen - outSampleCount) > 0) { int len = Math.min(outBufferLen - outSampleCount, this.Yp); buffers.consumeOutput(this.Y, 0, len); //for (int i = 0; i < len; i++) { // outBuffer[outBufferOffset + outSampleCount + i] = this.Y[i]; //} outSampleCount += len; for (int i = 0; i < this.Yp - len; i++) { this.Y[i] = this.Y[i + len]; } this.Yp -= len; } // If there are still output samples left, return now - we need // the full output buffer available to us... if (this.Yp != 0) { return inBufferUsed == 0 && outSampleCount == 0; } // Account for increased filter gain when using factors less than 1 if (factor < 1) { LpScl = (float) (LpScl * factor); } while (true) { // This is the maximum number of samples we can process // per loop iteration /* * #ifdef DEBUG * printf("XSize: %d Xoff: %d Xread: %d Xp: %d lastFlag: %d\n", * this.XSize, this.Xoff, this.Xread, this.Xp, lastFlag); #endif */ // Copy as many samples as we can from the input buffer into X int len = this.XSize - this.Xread; if (len >= inBufferLen - inBufferUsed) { len = inBufferLen - inBufferUsed; } buffers.produceInput(this.X, this.Xread, len); //for (int i = 0; i < len; i++) { // this.X[this.Xread + i] = inBuffer[inBufferOffset + inBufferUsed + i]; //} inBufferUsed += len; this.Xread += len; int Nx; if (lastBatch && (inBufferUsed == inBufferLen)) { // If these are the last samples, zero-pad the // end of the input buffer and make sure we process // all the way to the end Nx = this.Xread - this.Xoff; for (int i = 0; i < this.Xoff; i++) { this.X[this.Xread + i] = 0; } } else { Nx = this.Xread - 2 * this.Xoff; } /* * #ifdef DEBUG fprintf(stderr, "new len=%d Nx=%d\n", len, Nx); * #endif */ if (Nx <= 0) { break; } // Resample stuff in input buffer int Nout; if (factor >= 1) { // SrcUp() is faster if we can use it */ Nout = lrsSrcUp(this.X, this.Y, factor, /* &this.Time, */Nx, Nwing, LpScl, Imp, ImpD, interpFilt); } else { Nout = lrsSrcUD(this.X, this.Y, factor, /* &this.Time, */Nx, Nwing, LpScl, Imp, ImpD, interpFilt); } /* * #ifdef DEBUG * printf("Nout: %d\n", Nout); * #endif */ this.Time -= Nx; // Move converter Nx samples back in time this.Xp += Nx; // Advance by number of samples processed // Calc time accumulation in Time int Ncreep = (int) (this.Time) - this.Xoff; if (Ncreep != 0) { this.Time -= Ncreep; // Remove time accumulation this.Xp += Ncreep; // and add it to read pointer } // Copy part of input signal that must be re-used int Nreuse = this.Xread - (this.Xp - this.Xoff); for (int i = 0; i < Nreuse; i++) { this.X[i] = this.X[i + (this.Xp - this.Xoff)]; } /* #ifdef DEBUG printf("New Xread=%d\n", Nreuse); #endif */ this.Xread = Nreuse; // Pos in input buff to read new data into this.Xp = this.Xoff; this.Yp = Nout; // Copy as many samples as possible to the output buffer if (this.Yp != 0 && (outBufferLen - outSampleCount) > 0) { len = Math.min(outBufferLen - outSampleCount, this.Yp); buffers.consumeOutput(this.Y, 0, len); //for (int i = 0; i < len; i++) { // outBuffer[outBufferOffset + outSampleCount + i] = this.Y[i]; //} outSampleCount += len; for (int i = 0; i < this.Yp - len; i++) { this.Y[i] = this.Y[i + len]; } this.Yp -= len; } // If there are still output samples left, return now, // since we need the full output buffer available if (this.Yp != 0) { break; } } return inBufferUsed == 0 && outSampleCount == 0; }
Process a batch of samples. There is no guarantee that the input buffer will be drained. @param factor factor at which to resample this batch @param buffers sample buffer for producing input and consuming output @param lastBatch true if this is known to be the last batch of samples @return true iff resampling is complete (ie. no input samples consumed and no output samples produced)
Result::process
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/Resampler.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/Resampler.java
Apache-2.0
public boolean process(double factor, final FloatBuffer inputBuffer, boolean lastBatch, final FloatBuffer outputBuffer) { SampleBuffers sampleBuffers = new SampleBuffers() { public int getInputBufferLength() { return inputBuffer.remaining(); } public int getOutputBufferLength() { return outputBuffer.remaining(); } public void produceInput(float[] array, int offset, int length) { inputBuffer.get(array, offset, length); } public void consumeOutput(float[] array, int offset, int length) { outputBuffer.put(array, offset, length); } }; return process(factor, sampleBuffers, lastBatch); }
Process a batch of samples. Convenience method for when the input and output are both floats. @param factor factor at which to resample this batch @param inputBuffer contains input samples in the range -1.0 to 1.0 @param outputBuffer output samples will be deposited here @param lastBatch true if this is known to be the last batch of samples @return true iff resampling is complete (ie. no input samples consumed and no output samples produced)
Result::process
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/Resampler.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/Resampler.java
Apache-2.0
public Result process(double factor, float[] inBuffer, int inBufferOffset, int inBufferLen, boolean lastBatch, float[] outBuffer, int outBufferOffset, int outBufferLen) { FloatBuffer inputBuffer = FloatBuffer.wrap(inBuffer, inBufferOffset, inBufferLen); FloatBuffer outputBuffer = FloatBuffer.wrap(outBuffer, outBufferOffset, outBufferLen); process(factor, inputBuffer, lastBatch, outputBuffer); return new Result(inputBuffer.position() - inBufferOffset, outputBuffer.position() - outBufferOffset); }
Process a batch of samples. Alternative interface if you prefer to work with arrays. @param factor resampling rate for this batch @param inBuffer array containing input samples in the range -1.0 to 1.0 @param inBufferOffset offset into inBuffer at which to start processing @param inBufferLen number of valid elements in the inputBuffer @param lastBatch pass true if this is the last batch of samples @param outBuffer array to hold the resampled data @param outBufferOffset Offset in the output buffer. @param outBufferLen Output buffer length. @return the number of samples consumed and generated
Result::process
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/Resampler.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/Resampler.java
Apache-2.0
private int lrsSrcUp(float[] X, float[] Y, double factor, int Nx, int Nwing, float LpScl, float[] Imp, float[] ImpD, boolean Interp) { float[] Xp_array = X; int Xp_index; float[] Yp_array = Y; int Yp_index = 0; float v; double CurrentTime = this.Time; double dt; // Step through input signal double endTime; // When Time reaches EndTime, return to user dt = 1.0 / factor; // Output sampling period endTime = CurrentTime + Nx; while (CurrentTime < endTime) { double LeftPhase = CurrentTime - Math.floor(CurrentTime); double RightPhase = 1.0 - LeftPhase; Xp_index = (int) CurrentTime; // Ptr to current input sample // Perform left-wing inner product v = FilterKit.lrsFilterUp(Imp, ImpD, Nwing, Interp, Xp_array, Xp_index++, LeftPhase, -1); // Perform right-wing inner product v += FilterKit.lrsFilterUp(Imp, ImpD, Nwing, Interp, Xp_array, Xp_index, RightPhase, 1); v *= LpScl; // Normalize for unity filter gain Yp_array[Yp_index++] = v; // Deposit output CurrentTime += dt; // Move to next sample by time increment } this.Time = CurrentTime; return Yp_index; // Return the number of output samples }
Process a batch of samples. Alternative interface if you prefer to work with arrays. @param factor resampling rate for this batch @param inBuffer array containing input samples in the range -1.0 to 1.0 @param inBufferOffset offset into inBuffer at which to start processing @param inBufferLen number of valid elements in the inputBuffer @param lastBatch pass true if this is the last batch of samples @param outBuffer array to hold the resampled data @param outBufferOffset Offset in the output buffer. @param outBufferLen Output buffer length. @return the number of samples consumed and generated public Result process(double factor, float[] inBuffer, int inBufferOffset, int inBufferLen, boolean lastBatch, float[] outBuffer, int outBufferOffset, int outBufferLen) { FloatBuffer inputBuffer = FloatBuffer.wrap(inBuffer, inBufferOffset, inBufferLen); FloatBuffer outputBuffer = FloatBuffer.wrap(outBuffer, outBufferOffset, outBufferLen); process(factor, inputBuffer, lastBatch, outputBuffer); return new Result(inputBuffer.position() - inBufferOffset, outputBuffer.position() - outBufferOffset); } /* Sampling rate up-conversion only subroutine; Slightly faster than down-conversion;
Result::lrsSrcUp
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/resample/Resampler.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/resample/Resampler.java
Apache-2.0
public DelayEffect(double echoLength,double decay,double sampleRate) { this.sampleRate = sampleRate; setDecay(decay); setEchoLength(echoLength); applyNewEchoLength(); }
@param echoLength in seconds @param sampleRate the sample rate in Hz. @param decay The decay of the echo, a value between 0 and 1. 1 meaning no decay, 0 means immediate decay (not echo effect).
DelayEffect::DelayEffect
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/effects/DelayEffect.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/effects/DelayEffect.java
Apache-2.0
public void setEchoLength(double newEchoLength){ this.newEchoLength = newEchoLength; }
@param newEchoLength A new echo buffer length in seconds.
DelayEffect::setEchoLength
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/effects/DelayEffect.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/effects/DelayEffect.java
Apache-2.0
public void setDecay(double newDecay){ this.decay = (float) newDecay; }
A decay, should be a value between zero and one. @param newDecay the new decay (preferably between zero and one).
DelayEffect::setDecay
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/effects/DelayEffect.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/effects/DelayEffect.java
Apache-2.0
public FlangerEffect(double maxFlangerLength, double wet, double sampleRate, double lfoFrequency) { this.flangerBuffer = new float[(int) (sampleRate * maxFlangerLength)]; this.sampleRate = sampleRate; this.lfoFrequency = lfoFrequency; this.wet = (float) wet; this.dry = (float) (1 - wet); }
@param maxFlangerLength in seconds @param wet The 'wetness' of the flanging effect. A value between 0 and 1. Zero meaning no flanging effect in the resulting signal, one means total flanging effect and no original signal left. The dryness of the signal is determined by dry = "1-wet". @param sampleRate the sample rate in Hz. @param lfoFrequency in Hertz
FlangerEffect::FlangerEffect
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
Apache-2.0
public void setFlangerLength(double flangerLength) { flangerBuffer = new float[(int) (sampleRate * flangerLength)]; }
Set the new length of the delay LineWavelet. @param flangerLength The new length of the delay LineWavelet, in seconds.
FlangerEffect::setFlangerLength
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
Apache-2.0
public void setLFOFrequency(double lfoFrequency) { this.lfoFrequency = lfoFrequency; }
Sets the frequency of the LFO (sine wave), in Hertz. @param lfoFrequency The new LFO frequency in Hertz.
FlangerEffect::setLFOFrequency
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
Apache-2.0
public void setWet(double wet) { this.wet = (float) wet; this.dry = (float) (1 - wet); }
Sets the wetness and dryness of the effect. Should be a value between zero and one (inclusive), the dryness is determined by 1-wet. @param wet A value between zero and one (inclusive) that determines the wet and dryness of the resulting mix.
FlangerEffect::setWet
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/effects/FlangerEffect.java
Apache-2.0
public IIRFilter(float freq, float sampleRate) { this.sampleRate = sampleRate; this.frequency = freq; calcCoeff(); in = new float[a.length]; out = new float[b.length]; }
Constructs an IIRFilter with the given cutoff frequency that will be used to filter audio recorded at <code>sampleRate</code>. @param freq the cutoff frequency @param sampleRate the sample rate of audio to be filtered
IIRFilter::IIRFilter
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/filters/IIRFilter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/filters/IIRFilter.java
Apache-2.0
protected final float getFrequency() { return frequency; }
Returns the cutoff frequency (in Hz). @return the current cutoff frequency (in Hz).
IIRFilter::getFrequency
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/filters/IIRFilter.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/filters/IIRFilter.java
Apache-2.0
public BandPass(float freq, float bandWidth, float sampleRate) { super(freq, sampleRate); setBandWidth(bandWidth); }
Constructs a band pass filter with the requested center frequency, bandwidth and sample rate. @param freq the center frequency of the band to pass (in Hz) @param bandWidth the width of the band to pass (in Hz) @param sampleRate the sample rate of audio that will be filtered by this filter
BandPass::BandPass
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/filters/BandPass.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/filters/BandPass.java
Apache-2.0
public void setBandWidth(float bandWidth) { bw = bandWidth / getSampleRate(); calcCoeff(); }
Sets the band width of the filter. Doing this will cause the coefficients to be recalculated. @param bandWidth the band width (in Hz)
BandPass::setBandWidth
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/filters/BandPass.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/filters/BandPass.java
Apache-2.0
public float getBandWidth() { return bw * getSampleRate(); }
Returns the band width of this filter. @return the band width (in Hz)
BandPass::getBandWidth
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/filters/BandPass.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/filters/BandPass.java
Apache-2.0
public AmplitudeLFO(){ this(1.5,0.75); }
Create a new low frequency oscillator with a default frequency (1.5Hz and scale 0.75)
AmplitudeLFO::AmplitudeLFO
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/synthesis/AmplitudeLFO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/synthesis/AmplitudeLFO.java
Apache-2.0
public AmplitudeLFO(double frequency, double scaleParameter){ this.frequency = frequency; this.scaleParameter = scaleParameter; phase = 0; }
Create a new low frequency oscillator @param frequency The frequency in Hz @param scaleParameter The scale between 0 and 1 to modify the amplitude.
AmplitudeLFO::AmplitudeLFO
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/synthesis/AmplitudeLFO.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/synthesis/AmplitudeLFO.java
Apache-2.0
public void transform(float[] s){ int m = s.length; assert isPowerOfTwo(m); int n = log2(m); int j = 2; int i = 1; for(int l = 0 ; l < n ; l++ ){ m = m/2; for(int k=0; k < m;k++){ float a = (s[j*k]+s[j*k + i])/2.0f; float c = (s[j*k]-s[j*k + i])/2.0f; if(preserveEnergy){ a = a/sqrtTwo; c = c/sqrtTwo; } s[j*k] = a; s[j*k+i] = c; } i = j; j = j * 2; } }
Does an in-place HaarWavelet wavelet transform. The length of data needs to be a power of two. It is based on the algorithm found in "Wavelets Made Easy" by Yves Nivergelt, page 24. @param s The data to transform.
HaarWaveletTransform::transform
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
Apache-2.0
public void inverseTransform(float[] data){ int m = data.length; assert isPowerOfTwo(m); int n = log2(m); int i = pow2(n-1); int j = 2 * i; m = 1; for(int l = n ; l >= 1; l--){ for(int k = 0; k < m ; k++){ float a = data[j*k]+data[j*k+i]; float a1 = data[j*k]-data[j*k+i]; if(preserveEnergy){ a = a*sqrtTwo; a1 = a1*sqrtTwo; } data[j*k] = a; data[j*k+i] = a1; } j = i; i = i /2; m = 2*m; } }
Does an in-place inverse HaarWavelet Wavelet Transform. The data needs to be a power of two. It is based on the algorithm found in "Wavelets Made Easy" by Yves Nivergelt, page 29. @param data The data to transform.
HaarWaveletTransform::inverseTransform
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
Apache-2.0
public static boolean isPowerOfTwo(int number) { if (number <= 0) { throw new IllegalArgumentException("number: " + number); } return (number & -number) == number; }
Checks if the number is a power of two. For performance it uses bit shift operators. e.g. 4 in binary format is "0000 0000 0000 0000 0000 0000 0000 0100"; and -4 is "1111 1111 1111 1111 1111 1111 1111 1100"; and 4 &amp; -4 will be "0000 0000 0000 0000 0000 0000 0000 0100"; @param number The number to check. @return True if the number is a power of two, false otherwise.
HaarWaveletTransform::isPowerOfTwo
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
Apache-2.0
public static int log2(int bits) { if (bits == 0) { return 0; } return 31 - Integer.numberOfLeadingZeros(bits); }
A quick and simple way to calculate log2 of integers. @param bits the integer @return log2(bits)
HaarWaveletTransform::log2
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
Apache-2.0
public static int pow2(int power) { return 1<<power; }
A quick way to calculate the power of two (2^power), by using bit shifts. @param power The power. @return 2^power
HaarWaveletTransform::pow2
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/HaarWaveletTransform.java
Apache-2.0
public HaarWithPolynomialInterpolationWavelet() { fourPt = new PolynomialInterpolation(); }
HaarWithPolynomialInterpolationWavelet class constructor
HaarWithPolynomialInterpolationWavelet::HaarWithPolynomialInterpolationWavelet
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
Apache-2.0
private void fill(float[] vec, float[] d, int N, int start) { int n = numPts; if (n > N) n = N; int end = start + n; int j = 0; for (int i = start; i < end; i++) { d[j] = vec[i]; j++; } } // fill
<p> Copy four points or <i>N</i> (which ever is less) data points from <i>vec</i> into <i>d</i> These points are the "known" points used in the polynomial interpolation. </p> @param vec the input data set on which the wavelet is calculated @param d an array into which <i>N</i> data points, starting at <i>start</i> are copied. @param N the number of polynomial interpolation points @param start the index in <i>vec</i> from which copying starts
HaarWithPolynomialInterpolationWavelet::fill
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
Apache-2.0
protected void interp(float[] vec, int N, int direction) { int half = N >> 1; float[] d = new float[numPts]; // int k = 42; for (int i = 0; i < half; i++) { float predictVal; if (i == 0) { if (half == 1) { // e.g., N == 2, and we use HaarWavelet interpolation predictVal = vec[0]; } else { fill(vec, d, N, 0); predictVal = fourPt.interpPoint(0.5f, half, d); } } else if (i == 1) { predictVal = fourPt.interpPoint(1.5f, half, d); } else if (i == half - 2) { predictVal = fourPt.interpPoint(2.5f, half, d); } else if (i == half - 1) { predictVal = fourPt.interpPoint(3.5f, half, d); } else { fill(vec, d, N, i - 1); predictVal = fourPt.interpPoint(1.5f, half, d); } int j = i + half; if (direction == forward) { vec[j] = vec[j] - predictVal; } else if (direction == inverse) { vec[j] = vec[j] + predictVal; } else { System.out .println("PolynomialWavelets::predict: bad direction value"); } } } // interp
<p> Predict an odd point from the even points, using 4-point polynomial interpolation. </p> <p> The four points used in the polynomial interpolation are the even points. We pretend that these four points are located at the x-coordinates 0,1,2,3. The first odd point interpolated will be located between the first and second even point, at 0.5. The next N-3 points are located at 1.5 (in the middle of the four points). The last two points are located at 2.5 and 3.5. For complete documentation see </p> <pre> <a href="http://www.bearcave.com/misl/misl_tech/wavelets/lifting/index.html"> http://www.bearcave.com/misl/misl_tech/wavelets/lifting/index.html</a> </pre> <p> The difference between the predicted (interpolated) value and the actual odd value replaces the odd value in the forward transform. </p> <p> As the recursive steps proceed, N will eventually be 4 and then 2. When N = 4, linear interpolation is used. When N = 2, HaarWavelet interpolation is used (the prediction for the odd value is that it is equal to the even value). </p> @param vec the input data on which the forward or inverse transform is calculated. @param N the area of vec over which the transform is calculated @param direction forward or inverse transform
HaarWithPolynomialInterpolationWavelet::interp
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
Apache-2.0
public void forwardTrans(float[] vec) { final int N = vec.length; for (int n = N; n > 1; n = n >> 1) { split(vec, n); predict(vec, n, forward); update(vec, n, forward); interp(vec, n, forward); } // for } // forwardTrans
<p> HaarWavelet transform extened with polynomial interpolation forward transform. </p> <p> This version of the forwardTrans function overrides the function in the LiftingSchemeBaseWavelet base class. This function introduces an extra polynomial interpolation stage at the end of the transform. </p>
HaarWithPolynomialInterpolationWavelet::forwardTrans
java
ZTFtrue/MonsterMusic
app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
https://github.com/ZTFtrue/MonsterMusic/blob/master/app/src/main/java/be/tarsos/dsp/wavelet/lift/HaarWithPolynomialInterpolationWavelet.java
Apache-2.0