public class AudioRecorderComponent

  1. Object
  2. Component
  3. Container
  4. AudioRecorderComponent

ImplementsActionSource, Animation, Editable, Iterable<Component>, StyleListener

A component for recording Audio from the device microphone.

Example usage

package com.codename1.samples;

import com.codename1.components.AudioRecorderComponent;
import com.codename1.components.ToastBar;
import com.codename1.io.File;
import com.codename1.io.FileSystemStorage;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.media.AsyncMedia;
import com.codename1.media.MediaManager;
import com.codename1.media.MediaRecorderBuilder;
import com.codename1.ui.Button;
import com.codename1.ui.CN;
import com.codename1.ui.Sheet;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.util.AsyncResource;

/**
 * This file was generated by [Codename One](https://www.codenameone.com/) for the purpose
 * of building native mobile applications using Java.
 */
public class AudioRecorderComponentSample {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });
    }

    public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("Audio Recorder Sample", BoxLayout.y());
        Button record = new Button("Record Audio");
        record.addActionListener(e->{
            recordAudio().onResult((res, err)->{
                if (err != null) {
                    Log.e(err);
                    ToastBar.showErrorMessage(err.getMessage());
                    return;
                }
                if (res == null) {
                    return;
                }
                try {
                    MediaManager.createMedia(res, false).play();
                } catch (IOException ex) {
                    Log.e(ex);
                    ToastBar.showErrorMessage(ex.getMessage());
                }
            });
        });
        hi.add(record);
        hi.show();
    }

    private AsyncResource recordAudio() {
        AsyncResource out = new AsyncResource<>();
        String mime = MediaManager.getAvailableRecordingMimeTypes()[0];
        String ext = mime.indexOf("mp3") != -1? "mp3" : mime.indexOf("wav") != -1 ? "wav" : mime.indexOf("aiff") != -1 ? "aiff" : "aac";
        MediaRecorderBuilder builder = new MediaRecorderBuilder()
                .path(new File("myaudio."+ext).getAbsolutePath())
                .mimeType(mime);

        final AudioRecorderComponent cmp = new AudioRecorderComponent(builder);
        final Sheet sheet = new Sheet(null, "Record Audio");
        sheet.getContentPane().setLayout(new com.codename1.ui.layouts.BorderLayout());
        sheet.getContentPane().add(com.codename1.ui.layouts.BorderLayout.CENTER, cmp);
        cmp.addActionListener(new com.codename1.ui.events.ActionListener() {
@Override
            public void actionPerformed(com.codename1.ui.events.ActionEvent e) {
                switch (cmp.getState()) {
                    case Accepted:
                        CN.getCurrentForm().getAnimationManager().flushAnimation(new Runnable() {
                            public void run() {
                                sheet.back();
                                sheet.addCloseListener(new ActionListener() {
@Override
                                    public void actionPerformed(ActionEvent evt) {
                                        sheet.removeCloseListener(this);
                                        out.complete(builder.getPath());
                                    }

                                });
                            }
                        });



                        break;
                    case Canceled:
                        FileSystemStorage fs = FileSystemStorage.getInstance();
                        if (fs.exists(builder.getPath())) {
                            FileSystemStorage.getInstance().delete(builder.getPath());
                        }
                        CN.getCurrentForm().getAnimationManager().flushAnimation(new Runnable() {
                            public void run() {
                                sheet.back();
                                sheet.addCloseListener(new ActionListener() {
@Override
                                    public void actionPerformed(ActionEvent evt) {
                                        sheet.removeCloseListener(this);
                                        out.complete(null);
                                    }

                                });
                            }
                        });


                        break;
                }
            }

        });
        sheet.addCloseListener(new com.codename1.ui.events.ActionListener() {
@Override
            public void actionPerformed(com.codename1.ui.events.ActionEvent e) {
                if (cmp.getState() != AudioRecorderComponent.RecorderState.Accepted && cmp.getState() != AudioRecorderComponent.RecorderState.Canceled) {
                    FileSystemStorage fs = FileSystemStorage.getInstance();
                    if (fs.exists(builder.getPath())) {
                        FileSystemStorage.getInstance().delete(builder.getPath());
                    }
                    CN.getCurrentForm().getAnimationManager().flushAnimation(new Runnable() {
                        public void run() {
                            out.complete(null);
                        }
                    });
                }
            }

        });
        sheet.show();
        return out;
    }


    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
        }
    }

    public void destroy() {
    }

}

This component enables a full recording workflow. When the component is first displayed, it provides a “Record” button to begin the recording.

While the recording is in progress, it provides a “Done” button and a “Pause” button. The “Pause” button allows pausing and continuing the recording. The “Done” button indicates the recording is done.

After the user presses “Done”, a preview screen is shown that allows the user to listen to the recording. Then can choose to either accept the recording, cancel it, or try again.

Nested types

enum AudioRecorderComponent.RecorderStateEnum for tracking the recorder state.

Constructors

public AudioRecorderComponent(MediaRecorderBuilder builder)Creates a new audio recorder for the settings specified by the given builder.

Methods

protected void initComponent()Allows subclasses to bind functionality that relies on fully initialized and “ready for action” component state
protected void deinitialize()Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.
public boolean animate()Allows the animation to reduce “repaint” calls when it returns false.
public AudioRecorderComponent.RecorderState getState()Gets the recording state.
public void addActionListener(ActionListener l)Adds a listener to be notified when the state changes.
public void removeActionListener(ActionListener l)Removes an action listener.
protected Dimension calcPreferredSize()Calculates the preferred size based on component content.

Inherited fields

Inherited methods

From Container

encloseIn, encloseIn, initLaf, getUIManager, setUIManager, isSurface, add, addAll, add, add, add, add, add, getLeadComponent, setLeadComponent, getLeadParent, keyPressed, keyReleased, getLayout, setLayout, invalidate, setShouldLayout, setShouldCalcPreferredSize, getLayoutWidth, getLayoutHeight, applyRTL, constrainWidthWhenScrollable, constrainHeightWhenScrollable, addComponent, addComponent, addComponent, addComponent, replaceAndWait, replaceAndWait, replace, replaceAndWait, replace, createReplaceTransition, isEnabled, setEnabled, removeComponent, cancelRepaints, flushReplace, removeAll, revalidateWithAnimationSafety, revalidate, revalidateLater, forceRevalidate, clearClientProperties, paint, paintGlass, layoutContainer, isSafeArea, setSafeArea, isSafeAreaRoot, getSafeAreaRoot, setSafeAreaRoot, getComponentCount, getComponentAt, getComponentIndex, contains, scrollComponentToVisible, getClosestComponentTo, getResponderAt, getComponentAt, findDropTargetAt, pointerPressed, paramString, refreshTheme, isScrollableX, setScrollableX, isScrollableY, setScrollableY, getSideGap, getBottomGap, setScrollable, setCellRenderer, getScrollIncrement, setScrollIncrement, findFirstFocusable, dragInitiated, fireClicked, isSelectableInteraction, getGridPosY, paintComponentBackground, getGridPosX, animateHierarchyAndWait, createAnimateHierarchy, animateHierarchy, animateHierarchyFadeAndWait, createAnimateHierarchyFade, animateHierarchyFade, animateLayoutFadeAndWait, createAnimateLayoutFadeAndWait, animateLayoutFade, createAnimateLayoutFade, animateLayoutAndWait, animateLayout, updateTabIndices, createAnimateLayout, drop, createAnimateMotion, morph, morphAndWait, animateUnlayout, animateUnlayoutAndWait, createAnimateUnlayout, getChildrenAsList, iterator, iterator

From Component

setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, 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, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, 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, drawDraggedImage, draggingOver, dragEnter, dragExit, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerReleased, longPointerPress, pointerReleased, 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, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, refreshTheme, refreshTheme, isDragActivated, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, 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, 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

AudioRecorderComponent

public AudioRecorderComponent(MediaRecorderBuilder builder)
Creates a new audio recorder for the settings specified by the given builder.

Parameters

builder MediaRecorderBuilder
The settings for creating the media recorder.

Method details

initComponent

protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and “ready for action” component state

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.

animate

public boolean animate()
Allows the animation to reduce “repaint” calls when it returns false. It is called once for every frame. Frames are defined by the com.codename1.ui.Display class.

Returns

true if a repaint is desired or false if no repaint is necessary

getState

public AudioRecorderComponent.RecorderState getState()
Gets the recording state. Use this method to check whether the user accepted the recording, or canceled the recording.

Returns

A RecorderState.

addActionListener

public void addActionListener(ActionListener l)
Adds a listener to be notified when the state changes. Only transitions to the RecorderState#Accepted and RecorderState#Canceled states result in an event.

Parameters

l ActionListener
The listener

removeActionListener

public void removeActionListener(ActionListener l)
Removes an action 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