Search in sources :

Example 1 with MediaRecorderBuilder

use of com.codename1.media.MediaRecorderBuilder in project CodenameOne by codenameone.

the class AudioBufferSample method lowLevelUsageSample.

private void lowLevelUsageSample() {
    // Step 1: Create your audio buffer
    // This can be any size you like really.
    int bufferSize = 256;
    // Audio buffer path
    String path = "mybuffer.pcm";
    // Can be any string, as it doesn't correspond
    // to a real file.  It is just used internally
    // to identify audio buffers.
    AudioBuffer audioBuffer = MediaManager.getAudioBuffer(path, true, bufferSize);
    float[] myFloatBuffer = new float[bufferSize];
    // This float array will be used to copy data out of the audioBuffer
    // Step 2: Add callback to audio buffer
    audioBuffer.addCallback(floatSamples -> {
        // This callback will be called whenever the contents of the data buffer
        // are changed.
        // This is your "net" to grab the raw PCM samples.
        // floatSamples is a float[] array with the PCM samples. Each sample
        // ranges from -1 to 1.
        // IMPORTANT!: This callback is not run on the EDT.  It is called
        // on an internal audio capture thread.
        audioBuffer.copyTo(myFloatBuffer);
    // All of the new PCM data in in the myFloatBuffer array
    // Do what you like with it - send it to a server, save it to a file,
    // etc...
    });
    // Step 3: Create a MediaRecorder
    MediaRecorderBuilder mrb = new MediaRecorderBuilder().path(path).redirectToAudioBuffer(true);
    try {
        Media recorder = MediaManager.createMediaRecorder(mrb);
        // This actually starts recording.
        recorder.play();
        // Record for 5 seconds... use a timer to stop the recorder after that
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                recorder.cleanup();
            }
        }, 5000);
    } catch (IOException ex) {
        Log.p("Failed to create media recorder");
        Log.e(ex);
    }
}
Also used : MediaRecorderBuilder(com.codename1.media.MediaRecorderBuilder) Timer(java.util.Timer) TimerTask(java.util.TimerTask) Media(com.codename1.media.Media) AudioBuffer(com.codename1.media.AudioBuffer) IOException(java.io.IOException)

Example 2 with MediaRecorderBuilder

use of com.codename1.media.MediaRecorderBuilder in project CodenameOne by codenameone.

the class CodenameOneImplementation method captureAudio.

/**
 * Captures a audio and notifies with the raw data when available
 * @param response callback for the resulting data
 */
public void captureAudio(final MediaRecorderBuilder recordingOptions, final com.codename1.ui.events.ActionListener response) {
    final MediaRecorderBuilder builder = recordingOptions == null ? new MediaRecorderBuilder() : recordingOptions;
    if (!builder.isRedirectToAudioBuffer() && builder.getPath() == null) {
        builder.path(new com.codename1.io.File("tmpaudio.wav").getAbsolutePath());
    }
    if (!builder.isRedirectToAudioBuffer() && builder.getMimeType() == null) {
        builder.mimeType("audio/wav");
    }
    System.out.println("in captureAudio " + recordingOptions.isRedirectToAudioBuffer());
    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);
                                    response.actionPerformed(new com.codename1.ui.events.ActionEvent(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);
                                    response.actionPerformed(new com.codename1.ui.events.ActionEvent(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() {
                        response.actionPerformed(new com.codename1.ui.events.ActionEvent(null));
                    }
                });
            }
        }
    });
    sheet.show();
// capture(response, new String[] {"wav", "mp3", "aac"}, "*.wav;*.mp3;*.aac");
}
Also used : MediaRecorderBuilder(com.codename1.media.MediaRecorderBuilder) ActionEvent(com.codename1.ui.events.ActionEvent) FileSystemStorage(com.codename1.io.FileSystemStorage) ActionEvent(com.codename1.ui.events.ActionEvent) ActionListener(com.codename1.ui.events.ActionListener) BorderLayout(com.codename1.ui.layouts.BorderLayout) ActionListener(com.codename1.ui.events.ActionListener) com.codename1.ui(com.codename1.ui) AudioRecorderComponent(com.codename1.components.AudioRecorderComponent)

Example 3 with MediaRecorderBuilder

use of com.codename1.media.MediaRecorderBuilder in project CodenameOne by codenameone.

the class AudioBufferSample method start.

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("Capture", BoxLayout.y());
    hi.setToolbar(new Toolbar());
    Style s = UIManager.getInstance().getComponentStyle("Title");
    FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_MIC, s);
    FileSystemStorage fs = FileSystemStorage.getInstance();
    String recordingsDir = fs.getAppHomePath() + "recordings/";
    fs.mkdir(recordingsDir);
    try {
        for (String file : fs.listFiles(recordingsDir)) {
            MultiButton mb = new MultiButton(file.substring(file.lastIndexOf("/") + 1));
            mb.addActionListener((e) -> {
                try {
                    Media m = MediaManager.createMedia(recordingsDir + file, false);
                    m.play();
                } catch (Throwable err) {
                    Log.e(err);
                }
            });
            hi.add(mb);
        }
        hi.getToolbar().addCommandToRightBar("", icon, (ev) -> {
            try {
                String path = "tmpBuffer.pcm";
                int wavSampleRate = 16000;
                WAVWriter wavFileWriter = new WAVWriter(new File("tmpBuffer.wav"), wavSampleRate, 1, 16);
                AudioBuffer audioBuffer = MediaManager.getAudioBuffer(path, true, 64);
                MediaRecorderBuilder options = new MediaRecorderBuilder().audioChannels(1).redirectToAudioBuffer(true).path(path);
                System.out.println("Builder isredirect? " + options.isRedirectToAudioBuffer());
                float[] byteBuffer = new float[audioBuffer.getMaxSize()];
                audioBuffer.addCallback(buf -> {
                    if (buf.getSampleRate() > wavSampleRate) {
                        buf.downSample(wavSampleRate);
                    }
                    buf.copyTo(byteBuffer);
                    try {
                        wavFileWriter.write(byteBuffer, 0, buf.getSize());
                    } catch (Throwable t) {
                        Log.e(t);
                    }
                });
                String file = Capture.captureAudio(options);
                wavFileWriter.close();
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MMM-dd-kk-mm");
                String fileName = sd.format(new Date());
                String filePath = recordingsDir + fileName;
                Util.copy(fs.openInputStream(new File("tmpBuffer.wav").getAbsolutePath()), fs.openOutputStream(filePath));
                MultiButton mb = new MultiButton(fileName);
                mb.addActionListener((e) -> {
                    try {
                        Media m = MediaManager.createMedia(filePath, false);
                        m.play();
                    } catch (IOException err) {
                        Log.e(err);
                    }
                });
                hi.add(mb);
                hi.revalidate();
                if (file != null) {
                    System.out.println(file);
                }
            } catch (Throwable err) {
                Log.e(err);
            }
        });
    } catch (Throwable err) {
        Log.e(err);
    }
    hi.show();
}
Also used : MediaRecorderBuilder(com.codename1.media.MediaRecorderBuilder) Form(com.codename1.ui.Form) FileSystemStorage(com.codename1.io.FileSystemStorage) Media(com.codename1.media.Media) IOException(java.io.IOException) WAVWriter(com.codename1.media.WAVWriter) Date(java.util.Date) Style(com.codename1.ui.plaf.Style) AudioBuffer(com.codename1.media.AudioBuffer) FontImage(com.codename1.ui.FontImage) MultiButton(com.codename1.components.MultiButton) File(com.codename1.io.File) SimpleDateFormat(com.codename1.l10n.SimpleDateFormat) Toolbar(com.codename1.ui.Toolbar)

Example 4 with MediaRecorderBuilder

use of com.codename1.media.MediaRecorderBuilder in project CodenameOne by codenameone.

the class AudioRecorderComponentSample method recordAudio.

private AsyncResource<String> recordAudio() {
    AsyncResource<String> 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;
}
Also used : MediaRecorderBuilder(com.codename1.media.MediaRecorderBuilder) ActionEvent(com.codename1.ui.events.ActionEvent) FileSystemStorage(com.codename1.io.FileSystemStorage) ActionEvent(com.codename1.ui.events.ActionEvent) ActionListener(com.codename1.ui.events.ActionListener) ActionListener(com.codename1.ui.events.ActionListener) AudioRecorderComponent(com.codename1.components.AudioRecorderComponent) AsyncResource(com.codename1.util.AsyncResource) File(com.codename1.io.File) Sheet(com.codename1.ui.Sheet)

Aggregations

MediaRecorderBuilder (com.codename1.media.MediaRecorderBuilder)4 FileSystemStorage (com.codename1.io.FileSystemStorage)3 AudioRecorderComponent (com.codename1.components.AudioRecorderComponent)2 File (com.codename1.io.File)2 AudioBuffer (com.codename1.media.AudioBuffer)2 Media (com.codename1.media.Media)2 ActionEvent (com.codename1.ui.events.ActionEvent)2 ActionListener (com.codename1.ui.events.ActionListener)2 IOException (java.io.IOException)2 MultiButton (com.codename1.components.MultiButton)1 SimpleDateFormat (com.codename1.l10n.SimpleDateFormat)1 WAVWriter (com.codename1.media.WAVWriter)1 com.codename1.ui (com.codename1.ui)1 FontImage (com.codename1.ui.FontImage)1 Form (com.codename1.ui.Form)1 Sheet (com.codename1.ui.Sheet)1 Toolbar (com.codename1.ui.Toolbar)1 BorderLayout (com.codename1.ui.layouts.BorderLayout)1 Style (com.codename1.ui.plaf.Style)1 AsyncResource (com.codename1.util.AsyncResource)1