Client API. The Codename One framework your app is built on: this runs on the device, not in a backend.

public class AudioWaveform

  1. Object
  2. Component
  3. AudioWaveform

ImplementsAnimation, 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.

A voice message waveform, partly played

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.

Constructors

public AudioWaveform()An empty waveform; call #setLevels(float[]).
public AudioWaveform(float[] levels)A waveform of the given levels.

Methods

protected void initUnselectedStyle(Style unselectedStyle)Can be overridden by subclasses to perform initialization when the unselected style is set to a new value.
public static float[] levelsFromPcm(short[] samples, int bars)Reduces raw 16 bit PCM samples to bars levels: the peak of each slice, scaled so the loudest bar is 1.
public float[] getLevels()The levels drawn, one per bar.
public final void setLevels(float[] levels)Sets the levels, one per bar, each clamped to 0 to 1.
public float getProgress()How much has played, 0 to 1.
public void setProgress(float progress)Sets how much has played, clamped to 0 to 1.
public boolean isSeekable()Whether tapping and dragging seek.
public void setSeekable(boolean seekable)Turns seeking by touch on or off.
public boolean isSeeking()True while the user drags across the waveform.
public void setBarSize(float barMM, float gapMM, float heightMM)Sets the bar geometry.
public void addActionListener(ActionListener l)Adds a listener called when the user seeks.
public void removeActionListener(ActionListener l)Removes a listener.
protected Dimension calcPreferredSize()Calculates the preferred size based on component content.
public void paint(Graphics g)This 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.
public void pointerPressed(int x, int y)If this Component is focused, the pointer pressed event will call this method
public void pointerDragged(int x, int y)If this Component is focused, the pointer dragged event will call this method
public void pointerReleased(int x, int y)If this Component is focused, the pointer released event will call this method
protected void deinitialize()Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.
protected boolean isStickyDrag()Returns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries.

Inherited fields

Inherited methods

From Component

setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, initLaf, getUIManager, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, clearClientProperties, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, fireClicked, isSelectableInteraction, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, isScrollableX, isScrollableY, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, getBottomGap, getSideGap, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, setShouldCalcPreferredSize, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyPressed, keyReleased, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, dragInitiated, drawDraggedImage, draggingOver, dragEnter, dragExit, drop, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerPressed, isDragAndDropOperation, pointerReleased, longPointerPress, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, getContextMenuCommands, setContextMenuCommands, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, getHoverStyle, setHoverStyle, isHovered, setHovered, setPressedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, paramString, refreshTheme, refreshTheme, refreshTheme, isDragActivated, getGridPosY, getGridPosX, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, setCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, initComponent, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, isEnabled, setEnabled, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyNames, getPropertyTypes, getPropertyTypeNames, getPropertyValue, setPropertyValue, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, cancelRepaints, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip

Constructor details

AudioWaveform

public AudioWaveform()
An empty waveform; call #setLevels(float[]).

AudioWaveform

public AudioWaveform(float[] levels)
A waveform of the given levels.

Parameters

levels float[]
one loudness per bar, 0 to 1

Method details

initUnselectedStyle

protected void initUnselectedStyle(Style unselectedStyle)
Can be overridden by subclasses to perform initialization when the unselected style is set to a new value.

Parameters

unselectedStyle Style
The unselected style.

levelsFromPcm

public static float[] levelsFromPcm(short[] samples, int bars)
Reduces raw 16 bit PCM samples to bars levels: the peak of each slice, scaled so the loudest bar is 1.

Parameters

samples short[]
the PCM samples
bars int
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 float[]
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 float
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 boolean
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 float
each bar’s width in millimetres
gapMM float
the space between bars in millimetres
heightMM float
the preferred height in millimetres

addActionListener

public void addActionListener(ActionListener l)
Adds a listener called when the user seeks.

Parameters

l ActionListener
the listener

removeActionListener

public void removeActionListener(ActionListener l)
Removes a listener.

Parameters

l ActionListener
the listener

calcPreferredSize

protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked lazily by getPreferred size.

Returns

the calculated preferred size based on component content

paint

public void paint(Graphics g)
This 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 Graphics
the component graphics

pointerPressed

public void pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method

Parameters

x int
the pointer x coordinate
y int
the pointer y coordinate

pointerDragged

public void pointerDragged(int x, int y)
If this Component is focused, the pointer dragged event will call this method

Parameters

x int
the pointer x coordinate
y int
the pointer y coordinate

pointerReleased

public void pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method

Parameters

x int
the pointer x coordinate
y int
the pointer y coordinate

deinitialize

protected void deinitialize()
Invoked 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.

isStickyDrag

protected boolean isStickyDrag()
Returns 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