TailOff doesn't work in Build a MIDI synthesizer

Hi, am I wrong or the tailOff doesn’t work in the Build a MIDI synthesizer demo?
I’ve followed the tutorial and if I change the tail value to 1.0 in the startNote method, the sound plays only a tic…

You shouldn’t be modifying the tailOff value in startNote(). If you want to change the length of the tail off then you need to modify the value that it is multiplied by in renderNextBlock() - for a shorter tail off multiply it by a value closer to 0 and for a longer tail off multiply it by a value closer to 1.0.

Ok, but how can I modify the tailOff private member from the MainComponent in the sliderValueChanged()?

You should use the slider to control the value that tailOff is multiplied by instead of modifying tailOff directly.

Ok, but how can I do that from the MainComponent?

My problem is to access a private member or the multiplier of the class SineWaveVoice.h from the MainComponent.cpp

I’ve tried to make a setter method and call it from Main with

SineWaveVoice::setTailOff(release.getValue());

But setTailOff isn’t a static method

You need some way of setting the factor that the tailOff is multiplied by, either by passing a reference to your MainContentComponent down to the SineWaveVoice class where it can get the value in the renderNextBlock method or by setting the value directly when the slider moves in your MainContentComponent. Here’s a really simple example of the latter:

/*
  ==============================================================================

   This file is part of the JUCE tutorials.
   Copyright (c) 2017 - ROLI Ltd.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
   WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
   PURPOSE, ARE DISCLAIMED.

  ==============================================================================
*/

/*******************************************************************************
 The block below describes the properties of this PIP. A PIP is a short snippet
 of code that can be read by the Projucer and used to generate a JUCE project.

 BEGIN_JUCE_PIP_METADATA

 name:             SynthUsingMidiInputTutorial
 version:          1.0.0
 vendor:           JUCE
 website:          http://juce.com
 description:      Synthesiser with midi input.

 dependencies:     juce_audio_basics, juce_audio_devices, juce_audio_formats,
                   juce_audio_processors, juce_audio_utils, juce_core,
                   juce_data_structures, juce_events, juce_graphics,
                   juce_gui_basics, juce_gui_extra
 exporters:        xcode_mac, vs2017, linux_make

 type:             Component
 mainClass:        MainContentComponent

 useLocalCopy:     1

 END_JUCE_PIP_METADATA

*******************************************************************************/


#pragma once

//==============================================================================
struct SineWaveSound   : public SynthesiserSound
{
    SineWaveSound() {}

    bool appliesToNote    (int) override        { return true; }
    bool appliesToChannel (int) override        { return true; }
};

//==============================================================================
struct SineWaveVoice   : public SynthesiserVoice
{
    SineWaveVoice() {}

    bool canPlaySound (SynthesiserSound* sound) override
    {
        return dynamic_cast<SineWaveSound*> (sound) != nullptr;
    }

    void startNote (int midiNoteNumber, float velocity,
                    SynthesiserSound*, int /*currentPitchWheelPosition*/) override
    {
        currentAngle = 0.0;
        level = velocity * 0.15;
        tailOff = 0.0;

        auto cyclesPerSecond = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
        auto cyclesPerSample = cyclesPerSecond / getSampleRate();

        angleDelta = cyclesPerSample * 2.0 * MathConstants<double>::pi;
    }

    void stopNote (float /*velocity*/, bool allowTailOff) override
    {
        if (allowTailOff)
        {
            if (tailOff == 0.0)
                tailOff = 1.0;
        }
        else
        {
            clearCurrentNote();
            angleDelta = 0.0;
        }
    }

    void pitchWheelMoved (int) override      {}
    void controllerMoved (int, int) override {}

    void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples) override
    {
        if (angleDelta != 0.0)
        {
            if (tailOff > 0.0) // [7]
            {
                while (--numSamples >= 0)
                {
                    auto currentSample = (float) (std::sin (currentAngle) * level * tailOff);

                    for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
                        outputBuffer.addSample (i, startSample, currentSample);

                    currentAngle += angleDelta;
                    ++startSample;

                    tailOff *= tailOffAmount; // [8]

                    if (tailOff <= 0.05)
                    {
                        clearCurrentNote(); // [9]

                        angleDelta = 0.0;
                        break;
                    }
                }
            }
            else
            {
                while (--numSamples >= 0) // [6]
                {
                    auto currentSample = (float) (std::sin (currentAngle) * level);

                    for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
                        outputBuffer.addSample (i, startSample, currentSample);

                    currentAngle += angleDelta;
                    ++startSample;
                }
            }
        }
    }

    double tailOffAmount = 0.99;
    
private:
    double currentAngle = 0.0, angleDelta = 0.0, level = 0.0, tailOff = 0.0;
};

//==============================================================================
class SynthAudioSource   : public AudioSource
{
public:
    SynthAudioSource (MidiKeyboardState& keyState)
        : keyboardState (keyState)
    {
        for (auto i = 0; i < 4; ++i)                // [1]
            synth.addVoice (new SineWaveVoice());

        synth.addSound (new SineWaveSound());       // [2]
    }

    void setUsingSineWaveSound()
    {
        synth.clearSounds();
    }

    void prepareToPlay (int /*samplesPerBlockExpected*/, double sampleRate) override
    {
        synth.setCurrentPlaybackSampleRate (sampleRate); // [3]
    }

    void releaseResources() override {}

    void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
    {
        bufferToFill.clearActiveBufferRegion();

        MidiBuffer incomingMidi;
        keyboardState.processNextMidiBuffer (incomingMidi, bufferToFill.startSample,
                                             bufferToFill.numSamples, true);       // [4]

        synth.renderNextBlock (*bufferToFill.buffer, incomingMidi,
                               bufferToFill.startSample, bufferToFill.numSamples); // [5]
    }
    
    void setTailOffAmount (double to)
    {
        for (int i = 0; i < synth.getNumVoices(); ++i)
            if (auto* v = dynamic_cast<SineWaveVoice*> (synth.getVoice (i)))
                v->tailOffAmount = to;
    }

private:
    MidiKeyboardState& keyboardState;
    Synthesiser synth;
};

//==============================================================================
class MainContentComponent   : public AudioAppComponent,
                               private Timer
{
public:
    MainContentComponent()
        : synthAudioSource  (keyboardState),
          keyboardComponent (keyboardState, MidiKeyboardComponent::horizontalKeyboard)
    {
        addAndMakeVisible (keyboardComponent);

        tailOffSlider.setSkewFactor (5.0);
        tailOffSlider.setRange (0.99, 1.0, 0.0000001);
        addAndMakeVisible (tailOffSlider);
        tailOffSlider.onValueChange = [this] { synthAudioSource.setTailOffAmount (tailOffSlider.getValue()); };
        
        setAudioChannels (0, 2);
        
        setSize (600, 160);
        startTimer (400);
    }

    ~MainContentComponent()
    {
        shutdownAudio();
    }

    void resized() override
    {
        auto bounds = getLocalBounds().reduced (5);
        
        tailOffSlider.setBounds (bounds.removeFromTop (30));
        bounds.removeFromTop (5);
        keyboardComponent.setBounds (bounds);
    }

    void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override
    {
        synthAudioSource.prepareToPlay (samplesPerBlockExpected, sampleRate);
    }

    void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
    {
        synthAudioSource.getNextAudioBlock (bufferToFill);
    }

    void releaseResources() override
    {
        synthAudioSource.releaseResources();
    }

private:
    void timerCallback() override
    {
        keyboardComponent.grabKeyboardFocus();
        stopTimer();
    }

    //==========================================================================
    SynthAudioSource synthAudioSource;
    MidiKeyboardState keyboardState;
    MidiKeyboardComponent keyboardComponent;
    
    Slider tailOffSlider;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainContentComponent)
};

Thanks a lot! That works great! (But I can’t understand why in the constructor of SineWaveVoice, the tailOff is set to 0.0, and in the renderNextBlock the if statement of

if (tailOff > 0.0) {...} 

runs like the tailOff is major of 0.0 )

The code enclosed in the if (tailOff > 0.0) block will only be executed when the note has been released and allowTailOff is true (see the code in the stopNote() method). It multiplies the level of the sample by a decaying value to simulate a release envelope.

Ah ha!! Thanks, I understand now: the tailOff is set to 1.0 in the stopNote()…
I didn’t saw this… :slight_smile:

And if I want to add an attack parameter? How can I calculate the attackMultiplier?
I think I have to do something like that:

void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples) override
{
    if (angleDelta != 0.0)
    {
        if (tailOff > 0.0)
        {
            while (--numSamples >= 0)
            {
                auto currentSample = (float) (std::sin (currentAngle) * level * tailOff);
                
                for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
                    outputBuffer.addSample(i, startSample, currentSample);
                    
                currentAngle += angleDelta;
                ++startSample;
                    
                tailOff *= tailOffAmount;
                
                if (tailOff <= 0.005)
                {
                    clearCurrentNote();
                        
                    angleDelta = 0.0;
                    break;
                }
            }
        }
        else
        {
            while (--numSamples >= 0)
            {
                auto currentSample = (float) (std::sin (currentAngle) * level * attack); // [1] Multiply the amplitude by an attack value
                
                for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
                    outputBuffer.addSample(i, startSample, currentSample);
                    
                currentAngle += angleDelta;
                ++startSample;
                
                attack *= attackAmount;  // [2] multiply the attack value per an attack amount
            }
        }
    }
}

Isn’t it?