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.

  • 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

      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