# Class AudioRecorderComponent

java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.AudioRecorderComponent

All Implemented Interfaces:
  `Animation, Editable, ActionSource, StyleListener, Iterable<Component>`

public class AudioRecorderComponent extends Container implements ActionSource

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 Class Summary

  Nested Classes
  Modifier and Type
  Class
  Description
  `static enum`
  `AudioRecorderComponent.RecorderState`
  Enum for tracking the recorder state.

- ## 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

  Constructors
  Constructor
  Description
  `AudioRecorderComponent(MediaRecorderBuilder builder)`
  Creates a new audio recorder for the settings specified by the given builder.

- ## Method Summary

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

  ### Methods inherited from class Container

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

  ### Methods inherited from class Component

  `accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, 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, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getUIID, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyRepeated, laidOut, longKeyPress, longPointerPress, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, 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, 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, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains`

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait`

  ### Methods inherited from interface Iterable

  `forEach`

- ## Constructor Details

  - ### AudioRecorderComponent

    public AudioRecorderComponent(MediaRecorderBuilder builder)

    Creates a new audio recorder for the settings specified by the given builder.

    ###### Parameters

    - `builder`: The settings for creating the media recorder.

- ## Method Details

  - ### initComponent

    protected void initComponent()
    Description copied from class: `Component`
    Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state
    Overrides:
      `initComponent` in class `Component`

  - ### deinitialize

    protected void deinitialize()
    Description copied from class: `Component`
    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.
    Overrides:
      `deinitialize` in class `Component`

  - ### animate

    public boolean animate()
    Description copied from class: `Component`

    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

    Specified by:
      `animate` in interface `Animation`
    Overrides:
      `animate` in class `Component`

  - ### 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`: The listener
    Specified by:
      `addActionListener` in interface `ActionSource`

  - ### removeActionListener

    public void removeActionListener(ActionListener l)

    Removes an action listener.

    ###### Parameters

    - `l`: The listener.
    Specified by:
      `removeActionListener` in interface `ActionSource`

  - ### calcPreferredSize

    protected Dimension calcPreferredSize()
    Description copied from class: `Container`

    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

    Overrides:
      `calcPreferredSize` in class `Container`