Class AudioWaveform
- All Implemented Interfaces:
Animation, Editable, StyleListener
The bars of an audio clip's loudness, with the played part in the accent colour: the waveform of a voice message, a recording or a podcast scrubber.

Form form = new Form("Voice message", BoxLayout.y());
// 16-bit samples, normally decoded from the recording
short[] samples = new short[4800];
for (int i = 0; i < samples.length; i++) {
samples[i] = (short) (Math.sin(i / 40.0) * 12000 * Math.sin(i / 900.0));
}
AudioWaveform wave = new AudioWaveform(AudioWaveform.levelsFromPcm(samples, 48));
wave.addActionListener(e -> Log.p("Seek to " + wave.getProgress()));
form.add(wave);
form.show();
// as playback advances (a Media's getTime() / getDuration()),
// unless the user's finger is on it
if (!wave.isSeeking()) {
wave.setProgress(0.25f);
}
Levels are fractions from 0 to 1, one per bar, and are drawn evenly across
the width. Tapping or dragging seeks: the progress follows the finger, and
action listeners fire once when it lifts, so the component doubles as the
clip's scrubber. Call
setSeekable(false) for a display only waveform.
UIIDs: AudioWaveform. The played bars take the foreground of
AudioWaveformPlayed and the rest the background of AudioWaveformTrack
when the theme defines them, and otherwise the theme's Slider colours.
-
Field Summary
Fields inherited from class Component
BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR -
Constructor Summary
ConstructorsConstructorDescriptionAn empty waveform; call#setLevels(float[]).AudioWaveform(float[] levels) A waveform of the given levels. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a listener called when the user seeks.protected DimensionCalculates the preferred size based on component content.protected voidInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.float[]The levels drawn, one per bar.floatHow much has played, 0 to 1.protected voidinitUnselectedStyle(Style unselectedStyle) Can be overridden by subclasses to perform initialization when the unselected style is set to a new value.booleanWhether tapping and dragging seek.booleanTrue while the user drags across the waveform.protected booleanReturns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries.static float[]levelsFromPcm(short[] samples, int bars) Reduces raw 16 bit PCM samples tobarslevels: the peak of each slice, scaled so the loudest bar is 1.voidThis method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.voidpointerDragged(int x, int y) If this Component is focused, the pointer dragged event will call this methodvoidpointerPressed(int x, int y) If this Component is focused, the pointer pressed event will call this methodvoidpointerReleased(int x, int y) If this Component is focused, the pointer released event will call this methodvoidRemoves a listener.voidsetBarSize(float barMM, float gapMM, float heightMM) Sets the bar geometry.final voidsetLevels(float[] levels) Sets the levels, one per bar, each clamped to 0 to 1.voidsetProgress(float progress) Sets how much has played, clamped to 0 to 1.voidsetSeekable(boolean seekable) Turns seeking by touch on or off.Methods inherited from class Component
accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addNativeDragOverListener, addNativeDropListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, canAcceptNativeDrop, cancelRepaints, clearClientProperties, consumesRawTextInput, contains, containsOrOwns, createNativeDragOperation, createStyleAnimation, deinitializeCustomStyle, deregisterFromAnimation, dragEnter, dragExit, dragFinished, draggingOver, dragInitiated, drawDraggedImage, drop, fireClicked, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAcceptedDropActions, getAcceptedDropMimeTypes, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBottomGap, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getContextMenuCommands, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getGridPosX, getGridPosY, getHeight, getHoverStyle, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeDragOperation, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSemantics, getSideGap, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getTopLevelContainer, getUIID, getUIManager, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initComponent, initCustomStyle, initDisabledStyle, initLaf, initPressedStyle, initSelectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isEnabled, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHovered, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isNativeDragSource, isNativeDropTarget, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollableX, isScrollableY, isScrollVisible, isSelectableInteraction, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyPressed, keyReleased, keyRepeated, laidOut, longKeyPress, longPointerPress, mouseWheel, nativeDragEnter, nativeDragExit, nativeDragOver, nativeDrop, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, paramString, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, putClientProperty, refreshTheme, refreshTheme, refreshTheme, registerForAnimation, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removeNativeDragOverListener, removeNativeDropListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAcceptedDropActions, setAcceptedDropMimeTypes, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCellRenderer, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setContextMenuCommands, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setEnabled, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setHovered, setHoverStyle, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNativeDragOperation, setNativeDragSource, setNativeDropTarget, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setShouldCalcPreferredSize, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stopScrollMomentum, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
-
Constructor Details
-
AudioWaveform
public AudioWaveform()An empty waveform; call#setLevels(float[]). -
AudioWaveform
public AudioWaveform(float[] levels) A waveform of the given levels.
Parameters
levels: one loudness per bar, 0 to 1
-
-
Method Details
-
initUnselectedStyle
Description copied from class:ComponentCan be overridden by subclasses to perform initialization when the unselected style is set to a new value.
Parameters
unselectedStyle: The unselected style.
- Overrides:
initUnselectedStylein classComponent
-
levelsFromPcm
public static float[] levelsFromPcm(short[] samples, int bars) Reduces raw 16 bit PCM samples to
barslevels: the peak of each slice, scaled so the loudest bar is 1.Parameters
-
samples: the PCM samples -
bars: how many levels to produce
Returns
the levels, 0 to 1
-
-
getLevels
public float[] getLevels()The levels drawn, one per bar.
Returns
a copy of the levels
-
setLevels
public final void setLevels(float[] levels) Sets the levels, one per bar, each clamped to 0 to 1.
Parameters
levels: the loudness of each bar
-
getProgress
public float getProgress()How much has played, 0 to 1.
Returns
the played fraction
-
setProgress
public void setProgress(float progress) Sets how much has played, clamped to 0 to 1.
Parameters
progress: the played fraction
-
isSeekable
public boolean isSeekable()Whether tapping and dragging seek.
Returns
true by default
-
setSeekable
public void setSeekable(boolean seekable) Turns seeking by touch on or off.
Parameters
seekable: false for a display only waveform
-
isSeeking
public boolean isSeeking()True while the user drags across the waveform. Listeners are not called during the drag, only when it ends, so
#setProgress(float)calls from playback can be skipped while this is true.Returns
whether a seek drag is in progress
-
setBarSize
public void setBarSize(float barMM, float gapMM, float heightMM) Sets the bar geometry.
Parameters
-
barMM: each bar's width in millimetres -
gapMM: the space between bars in millimetres -
heightMM: the preferred height in millimetres
-
-
addActionListener
Adds a listener called when the user seeks.
Parameters
l: the listener
-
removeActionListener
Removes a listener.
Parameters
l: the listener
-
calcPreferredSize
Description copied from class:ComponentCalculates the preferred size based on component content. This method is invoked lazily by getPreferred size.
Returns
the calculated preferred size based on component content
- Overrides:
calcPreferredSizein classComponent
-
paint
Description copied from class:ComponentThis method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.
Parameters
g: the component graphics
-
pointerPressed
public void pointerPressed(int x, int y) Description copied from class:ComponentIf this Component is focused, the pointer pressed event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerPressedin classComponent
-
-
pointerDragged
public void pointerDragged(int x, int y) Description copied from class:ComponentIf this Component is focused, the pointer dragged event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerDraggedin classComponent
-
-
pointerReleased
public void pointerReleased(int x, int y) Description copied from class:ComponentIf this Component is focused, the pointer released event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerReleasedin classComponent
-
-
deinitialize
protected void deinitialize()Description copied from class:ComponentInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method.- Overrides:
deinitializein classComponent
-
isStickyDrag
protected boolean isStickyDrag()Description copied from class:ComponentReturns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries. This is useful for spinners etc. where the motion might continue beyond the size of the component
Returns
false by default
- Overrides:
isStickyDragin classComponent
-