Login  Register

Re: SoundJLayer

Posted by basti on Oct 13, 2023; 8:04pm
URL: https://forum.jogamp.org/SoundJLayer-tp4043032p4043047.html

Hello jfpauly,
in addition to Julien's replies i would like to suggest a Java3D approach limited to WAV and AU files.
If you're not strictly bound to MP3, of course.

BackgroundSoundTest.java

greetings,
basti

EDIT:
I realised that parenting the BackgroundSound instance directly to the root BranchGroup is not suitable for use-cases in which
the sound is not needed anymore once a certain event occurs, and therefore is just hogging memory. To be able to detach it
from the scene it needs to be in it's own BranchGroup. So just in case someone stumbles upon this, a possible solution could be this:

/**
 * Implementation of BackgroundSound able to be detached from scene graph.
 *
 * @author basti
 */
public class DetachableBackgroundSound extends BackgroundSound {
   
    /* Parent of bgSound, e.g.: the root BranchGroup */
    private final BranchGroup parent;
   
    /* Immediate parent of this class, since only instances of
       BranchGroup can be detached from scene. */
    private final BranchGroup bgSound;

    /**
     * Creates new instance of DetachableBackgroundSound.
     * @param parent the BranchGroup to act as parent of bgSound
     */
    public DetachableBackgroundSound(BranchGroup parent) {
        this.parent = parent;
        this.bgSound = new BranchGroup();
       
        checkStateOfParent();
        setCapabilities();
        addToSceneGraph();
    }
   
    /**
     * Frees sound data and detaches BranchGroup containing sound from scene
     * graph.
     */
    public void detachFromSceneGraph() {
        setSoundData(null);
        bgSound.detach();
    }

    /**
     * Checks if parent BranchGroup has needed capability set.
     *
     * @throws IllegalStateException if capability must be set but parent is
     *      live
     * @throws IllegalStateException if capability must be set but parent is
     *      compiled
     */
    private void checkStateOfParent() {
        int capability = BranchGroup.ALLOW_CHILDREN_WRITE;
       
        if (!parent.getCapability(capability)) {
            if(parent.isCompiled()) {
                throw new IllegalStateException(
                    "Unable to set capability to write children, because " +
                    "parent BranchGroup is already compiled.");
            }
            else if(parent.isLive()) {
                throw new IllegalStateException(
                    "Unable to set capability to write children, because " +
                    "parent BranchGroup is already live.");
            }
            parent.setCapability(capability);
        }
    }

    private void setCapabilities() {
        bgSound.setCapability(BranchGroup.ALLOW_DETACH);
        setCapability(BackgroundSound.ALLOW_SOUND_DATA_WRITE);
    }

    private void addToSceneGraph() {
        bgSound.addChild(this);
        parent.addChild(bgSound);
    }
}