Search in sources :

Example 1 with Audio

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

the class AndroidImplementation method createMedia.

/**
 * @inheritDoc
 */
@Override
public Media createMedia(final String uri, boolean isVideo, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to play media")) {
        return null;
    }
    if (uri.startsWith("file://")) {
        return createMedia(removeFilePrefix(uri), isVideo, onCompletion);
    }
    File file = null;
    if (uri.indexOf(':') < 0) {
        // use a file object to play to try and workaround this issue:
        // http://code.google.com/p/android/issues/detail?id=4124
        file = new File(uri);
    }
    Media retVal;
    if (isVideo) {
        final AndroidImplementation.Video[] video = new AndroidImplementation.Video[1];
        final boolean[] flag = new boolean[1];
        final File f = file;
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                VideoView v = new VideoView(getActivity());
                v.setZOrderMediaOverlay(true);
                if (f != null) {
                    v.setVideoURI(Uri.fromFile(f));
                } else {
                    v.setVideoURI(Uri.parse(uri));
                }
                video[0] = new AndroidImplementation.Video(v, getActivity(), onCompletion);
                flag[0] = true;
                synchronized (flag) {
                    flag.notify();
                }
            }
        });
        while (!flag[0]) {
            synchronized (flag) {
                try {
                    flag.wait(100);
                } catch (InterruptedException ex) {
                }
            }
        }
        return video[0];
    } else {
        MediaPlayer player;
        if (file != null) {
            FileInputStream is = new FileInputStream(file);
            player = new MediaPlayer();
            player.setDataSource(is.getFD());
            player.prepare();
        } else {
            player = MediaPlayer.create(getActivity(), Uri.parse(uri));
        }
        retVal = new Audio(getActivity(), player, null, onCompletion);
    }
    return retVal;
}
Also used : Media(com.codename1.media.Media) Audio(com.codename1.media.Audio) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) FileInputStream(java.io.FileInputStream) MediaPlayer(android.media.MediaPlayer)

Example 2 with Audio

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

the class AndroidImplementation method createMedia.

/**
 * @inheritDoc
 */
@Override
public Media createMedia(InputStream stream, String mimeType, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to play media")) {
        return null;
    }
    boolean isVideo = mimeType.contains("video");
    if (!isVideo && stream instanceof FileInputStream) {
        MediaPlayer player = new MediaPlayer();
        player.setDataSource(((FileInputStream) stream).getFD());
        player.prepare();
        return new Audio(getActivity(), player, stream, onCompletion);
    }
    String extension = MimeTypeMap.getFileExtensionFromUrl(mimeType);
    final File temp = File.createTempFile("mtmp", extension == null ? "dat" : extension);
    temp.deleteOnExit();
    OutputStream out = createFileOuputStream(temp);
    byte[] buf = new byte[256];
    int len = 0;
    while ((len = stream.read(buf, 0, buf.length)) > -1) {
        out.write(buf, 0, len);
    }
    out.close();
    stream.close();
    final Runnable finish = new Runnable() {

        @Override
        public void run() {
            if (onCompletion != null) {
                Display.getInstance().callSerially(onCompletion);
                // makes sure the file is only deleted after the onCompletion was invoked
                Display.getInstance().callSerially(new Runnable() {

                    @Override
                    public void run() {
                        temp.delete();
                    }
                });
                return;
            }
            temp.delete();
        }
    };
    if (isVideo) {
        final AndroidImplementation.Video[] retVal = new AndroidImplementation.Video[1];
        final boolean[] flag = new boolean[1];
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                VideoView v = new VideoView(getActivity());
                v.setZOrderMediaOverlay(true);
                v.setVideoURI(Uri.fromFile(temp));
                retVal[0] = new AndroidImplementation.Video(v, getActivity(), finish);
                flag[0] = true;
                synchronized (flag) {
                    flag.notify();
                }
            }
        });
        while (!flag[0]) {
            synchronized (flag) {
                try {
                    flag.wait(100);
                } catch (InterruptedException ex) {
                }
            }
        }
        return retVal[0];
    } else {
        return createMedia(createFileInputStream(temp), mimeType, finish);
    }
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) FileInputStream(java.io.FileInputStream) Paint(android.graphics.Paint) Audio(com.codename1.media.Audio) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) MediaPlayer(android.media.MediaPlayer)

Example 3 with Audio

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

the class GameCanvasImplementation method captureAudio.

public void captureAudio(ActionListener response) {
    captureResponse = response;
    try {
        final Form current = Display.getInstance().getCurrent();
        final MMAPIPlayer player = MMAPIPlayer.createPlayer("capture://audio", null);
        RecordControl record = (RecordControl) player.nativePlayer.getControl("RecordControl");
        if (record == null) {
            player.cleanup();
            throw new RuntimeException("Capture Audio is not supported on this device");
        }
        final Form cam = new Form();
        cam.setTransitionInAnimator(CommonTransitions.createEmpty());
        cam.setTransitionOutAnimator(CommonTransitions.createEmpty());
        cam.setLayout(new BorderLayout());
        cam.show();
        player.play();
        final Label time = new Label("0:00");
        cam.addComponent(BorderLayout.SOUTH, time);
        cam.revalidate();
        ActionListener l = new ActionListener() {

            boolean recording = false;

            OutputStream out = null;

            String audioPath = null;

            RecordControl record;

            public void actionPerformed(ActionEvent evt) {
                if (!recording) {
                    record = (RecordControl) player.nativePlayer.getControl("RecordControl");
                    recording = true;
                    String type = record.getContentType();
                    String prefix = "";
                    if (type.endsWith("wav")) {
                        prefix = ".wav";
                    } else if (type.endsWith("amr")) {
                        prefix = ".amr";
                    } else if (type.endsWith("3gpp")) {
                        prefix = ".3gp";
                    }
                    audioPath = getOutputMediaFile() + prefix;
                    try {
                        out = FileSystemStorage.getInstance().openOutputStream(audioPath);
                        record.setRecordStream(out);
                        record.startRecord();
                        cam.registerAnimated(new Animation() {

                            long current = System.currentTimeMillis();

                            long zero = current;

                            int sec = 0;

                            public boolean animate() {
                                long now = System.currentTimeMillis();
                                if (now - current > 1000) {
                                    current = now;
                                    sec++;
                                    return true;
                                }
                                return false;
                            }

                            public void paint(Graphics g) {
                                String txt = sec / 60 + ":" + sec % 60;
                                time.setText(txt);
                            }
                        });
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        System.out.println("failed to store audio to " + audioPath);
                    } finally {
                    }
                } else {
                    if (out != null) {
                        try {
                            record.stopRecord();
                            record.commit();
                            out.close();
                            player.cleanup();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    captureResponse.actionPerformed(new ActionEvent(audioPath));
                    current.showBack();
                }
            }
        };
        cam.addGameKeyListener(Display.GAME_FIRE, l);
        cam.addPointerReleasedListener(l);
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException("failed to start camera");
    }
}
Also used : Form(com.codename1.ui.Form) ActionEvent(com.codename1.ui.events.ActionEvent) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) RecordStoreException(javax.microedition.rms.RecordStoreException) MediaException(javax.microedition.media.MediaException) IOException(java.io.IOException) ConnectionNotFoundException(javax.microedition.io.ConnectionNotFoundException) Graphics(com.codename1.ui.Graphics) BorderLayout(com.codename1.ui.layouts.BorderLayout) ActionListener(com.codename1.ui.events.ActionListener) Animation(com.codename1.ui.animations.Animation) RecordControl(javax.microedition.media.control.RecordControl)

Example 4 with Audio

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

the class CodenameOneImplementation method createBackgroundMedia.

/**
 * Creates an audio media that can be played in the background.
 *
 * @param uri the uri of the media can start with jar://, file://, http://
 * (can also use rtsp:// if supported on the platform)
 *
 * @return Media a Media Object that can be used to control the playback
 * of the media
 *
 * @throws IOException if creation of media from the given URI has failed
 */
public Media createBackgroundMedia(String uri) throws IOException {
    if (uri.startsWith("jar://")) {
        uri = uri.substring(6);
        if (!uri.startsWith("/")) {
            uri = "/" + uri;
        }
        InputStream is = getResourceAsStream(this.getClass(), uri);
        String mime = "";
        if (uri.endsWith(".mp3")) {
            mime = "audio/mp3";
        } else if (uri.endsWith(".wav")) {
            mime = "audio/x-wav";
        } else if (uri.endsWith(".amr")) {
            mime = "audio/amr";
        } else if (uri.endsWith(".3gp")) {
            mime = "audio/3gpp";
        }
        return createMedia(is, mime, null);
    }
    return createMedia(uri, false, null);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) TarInputStream(com.codename1.io.tar.TarInputStream) InputStream(java.io.InputStream)

Example 5 with Audio

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

the class AndroidImplementation method captureAudio.

public void captureAudio(final ActionListener response) {
    if (!checkForPermission(Manifest.permission.RECORD_AUDIO, "This is required to record the audio")) {
        return;
    }
    try {
        final Form current = Display.getInstance().getCurrent();
        final File temp = File.createTempFile("mtmp", ".3gpp");
        temp.deleteOnExit();
        if (recorder != null) {
            recorder.release();
        }
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
        recorder.setOutputFile(temp.getAbsolutePath());
        final Form recording = new Form("Recording");
        recording.setTransitionInAnimator(CommonTransitions.createEmpty());
        recording.setTransitionOutAnimator(CommonTransitions.createEmpty());
        recording.setLayout(new BorderLayout());
        recorder.prepare();
        recorder.start();
        final Label time = new Label("00:00");
        time.getAllStyles().setAlignment(Component.CENTER);
        Font f = Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);
        f = f.derive(getDisplayHeight() / 10, Font.STYLE_PLAIN);
        time.getAllStyles().setFont(f);
        recording.addComponent(BorderLayout.CENTER, time);
        recording.registerAnimated(new Animation() {

            long current = System.currentTimeMillis();

            long zero = current;

            int sec = 0;

            public boolean animate() {
                long now = System.currentTimeMillis();
                if (now - current > 1000) {
                    current = now;
                    sec++;
                    return true;
                }
                return false;
            }

            public void paint(Graphics g) {
                int seconds = sec % 60;
                int minutes = sec / 60;
                String secStr = seconds < 10 ? "0" + seconds : "" + seconds;
                String minStr = minutes < 10 ? "0" + minutes : "" + minutes;
                String txt = minStr + ":" + secStr;
                time.setText(txt);
            }
        });
        Container south = new Container(new com.codename1.ui.layouts.GridLayout(1, 2));
        Command cancel = new Command("Cancel") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                if (recorder != null) {
                    recorder.stop();
                    recorder.release();
                    recorder = null;
                }
                current.showBack();
                response.actionPerformed(null);
            }
        };
        recording.setBackCommand(cancel);
        south.add(new com.codename1.ui.Button(cancel));
        south.add(new com.codename1.ui.Button(new Command("Save") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                if (recorder != null) {
                    recorder.stop();
                    recorder.release();
                    recorder = null;
                }
                current.showBack();
                response.actionPerformed(new ActionEvent(temp.getAbsolutePath()));
            }
        }));
        recording.addComponent(BorderLayout.SOUTH, south);
        recording.show();
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException("failed to start audio recording");
    }
}
Also used : ActionEvent(com.codename1.ui.events.ActionEvent) IOException(java.io.IOException) Font(com.codename1.ui.Font) Paint(android.graphics.Paint) BorderLayout(com.codename1.ui.layouts.BorderLayout) com.codename1.ui(com.codename1.ui) Animation(com.codename1.ui.animations.Animation) MediaRecorder(android.media.MediaRecorder) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

IOException (java.io.IOException)5 ConnectionNotFoundException (javax.microedition.io.ConnectionNotFoundException)4 MediaException (javax.microedition.media.MediaException)4 RecordStoreException (javax.microedition.rms.RecordStoreException)4 Media (com.codename1.media.Media)3 ActionEvent (com.codename1.ui.events.ActionEvent)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 File (java.io.File)3 RandomAccessFile (java.io.RandomAccessFile)3 Paint (android.graphics.Paint)2 MediaPlayer (android.media.MediaPlayer)2 BufferedOutputStream (com.codename1.io.BufferedOutputStream)2 Audio (com.codename1.media.Audio)2 Animation (com.codename1.ui.animations.Animation)2 BorderLayout (com.codename1.ui.layouts.BorderLayout)2 FileInputStream (java.io.FileInputStream)2 OutputStream (java.io.OutputStream)2 MediaRecorder (android.media.MediaRecorder)1 TarInputStream (com.codename1.io.tar.TarInputStream)1 com.codename1.ui (com.codename1.ui)1