Example usage for java.io FileInputStream getFD

List of usage examples for java.io FileInputStream getFD

Introduction

In this page you can find the example usage for java.io FileInputStream getFD.

Prototype

public final FileDescriptor getFD() throws IOException 

Source Link

Document

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.

Usage

From source file:com.fivehundredpxdemo.android.storage.ImageFetcher.java

/**
 * Download and resize a normal sized remote bitmap from a HTTP URL using a HTTP cache.
 * @param urlString The URL of the image to download
 * @return The scaled bitmap//w w  w .j  a v a 2s.  c o m
 */
private Bitmap processNormalBitmap(String urlString) {
    final String key = ImageCache.hashKeyForDisk(urlString);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (mHttpDiskCache != null) {
            try {
                snapshot = mHttpDiskCache.get(key);
                if (snapshot == null) {
                    Log.d(TAG, "processBitmap, not found in http cache, downloading...");
                    DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
                    if (editor != null) {
                        if (downloadUrlToStream(urlString, editor.newOutputStream(DISK_CACHE_INDEX))) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = mHttpDiskCache.get(key);
                }
                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();
                }
            } catch (IOException e) {
                Log.e(TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                Log.e(TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight);
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }
    return bitmap;
}

From source file:cut.ac.cy.my_tour_guide.gallery.ImageDownloader.java

private Bitmap processBitmap(String data) {
    if (BuildConfig.DEBUG) {
        Log.d(LOG_TAG, "processBitmap - " + data);
    }//from www  . j  a  va 2  s  . c  o  m

    final String key = ImageCache.hashKeyForDisk(data);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (HttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (HttpDiskCacheStarting) {
            try {
                HttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (HttpDiskCache != null) {
            try {
                snapshot = HttpDiskCache.get(key);
                if (snapshot == null) {
                    if (BuildConfig.DEBUG) {
                        Log.d(LOG_TAG, "processBitmap, not found in http cache, downloading...");
                    }
                    DiskLruCache.Editor editor = HttpDiskCache.edit(key);
                    if (editor != null) {
                        if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX))) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = HttpDiskCache.get(key);
                }
                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();
                }
            } catch (IOException e) {
                Log.e(LOG_TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                Log.e(LOG_TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        DeviceProperties device = new DeviceProperties(activity);

        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, device.getDeviceWidth(),
                device.getDeviceHeight());
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }
    return bitmap;
}

From source file:com.gtx.cooliris.imagecache.ImageFetcher.java

/**
 * The main process method, which will be called by the ImageWorker in the AsyncTask background
 * thread.//  w ww .j  a v a 2  s  .  c  o  m
 *
 * @param data The data to load the bitmap, in this case, a regular http URL
 * @return The downloaded and resized bitmap
 */
private Bitmap processBitmap(String data) {
    if (BuildConfig.DEBUG) {
        LogUtil.d(TAG, "processBitmap - " + data);
    }

    final String key = ImageCache.hashKeyForDisk(data);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot = null;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (mHttpDiskCache != null) {
            try {
                snapshot = mHttpDiskCache.get(key);
                if (snapshot == null) {
                    if (BuildConfig.DEBUG) {
                        LogUtil.d(TAG, "processBitmap, not found in http cache, downloading...");
                    }
                    DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
                    if (editor != null) {
                        if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX))) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = mHttpDiskCache.get(key);
                }
                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();
                }
            } catch (IOException e) {
                LogUtil.e(TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                LogUtil.e(TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache());
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }

    if (null != snapshot) {
        snapshot.close();
    }
    return bitmap;
}

From source file:com.Beat.RingdroidEditActivity.java

private synchronized void onPlay(int startPosition) {
    if (mIsPlaying) {
        handlePause();/*from  ww  w.  j av a2 s . c  o  m*/
        return;
    }

    if (mPlayer == null) {
        // Not initialized yet
        return;
    }

    try {
        mPlayStartMsec = mWaveformView.pixelsToMillisecs(startPosition);
        if (startPosition < mStartPos) {
            mPlayEndMsec = mWaveformView.pixelsToMillisecs(mStartPos);
        } else if (startPosition > mEndPos) {
            mPlayEndMsec = mWaveformView.pixelsToMillisecs(mMaxPos);
        } else {
            mPlayEndMsec = mWaveformView.pixelsToMillisecs(mEndPos);
        }

        mPlayStartOffset = 0;

        int startFrame = mWaveformView.secondsToFrames(mPlayStartMsec * 0.001);
        int endFrame = mWaveformView.secondsToFrames(mPlayEndMsec * 0.001);
        int startByte = mSoundFile.getSeekableFrameOffset(startFrame);
        int endByte = mSoundFile.getSeekableFrameOffset(endFrame);
        if (mCanSeekAccurately && startByte >= 0 && endByte >= 0) {
            try {
                mPlayer.reset();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                FileInputStream subsetInputStream = new FileInputStream(mFile.getAbsolutePath());
                mPlayer.setDataSource(subsetInputStream.getFD(), startByte, endByte - startByte);
                mPlayer.prepare();
                mPlayStartOffset = mPlayStartMsec;
            } catch (Exception e) {
                System.out.println("Exception trying to play file subset");
                mPlayer.reset();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(mFile.getAbsolutePath());
                mPlayer.prepare();
                mPlayStartOffset = 0;
            }
        }

        mPlayer.setOnCompletionListener(new OnCompletionListener() {
            public synchronized void onCompletion(MediaPlayer arg0) {
                handlePause();
            }
        });
        mIsPlaying = true;

        if (mPlayStartOffset == 0) {
            mPlayer.seekTo(mPlayStartMsec);
        }
        mPlayer.start();
        updateDisplay();
        enableDisableButtons();
    } catch (Exception e) {
        showFinalAlert(e, R.string.play_error);
        return;
    }
}

From source file:com.gtx.cooliris.imagecache.ImageFetcher.java

/**
 * Add by liulin.// w  w w  .  j av a2 s  .  c om
 * We use the {@link #org.apache.http.client.methods.HttpGet} to download image from network,
 * which can makes the socket cancel immediately if needed.
 * 
 * @param data The data to load the bitmap, in this case, a regular http URL
 * @param task The invoker.
 * 
 * @return The downloaded and resized bitmap.
 */
// Add by liulin
// We use the { org.apache.http.client.methods.HttpGet
//
private Bitmap processBitmap(String data, BitmapWorkerTask task) {
    if (BuildConfig.DEBUG) {
        LogUtil.d(TAG, "processBitmap - " + data);
    }

    final String key = ImageCache.hashKeyForDisk(data);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (mHttpDiskCache != null) {
            try {
                snapshot = mHttpDiskCache.get(key);
                if (snapshot == null) {
                    if (BuildConfig.DEBUG) {
                        LogUtil.d(TAG, "processBitmap, not found in http cache, downloading...");
                    }
                    DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
                    if (editor != null) {
                        OutputStream os = editor.newOutputStream(DISK_CACHE_INDEX);

                        // Copy local image if the file existed.
                        // Otherwise, download load it.
                        if (copyLocalImageToStream(data, os, task)) {
                            editor.commit();
                        } else {
                            if (downloadUrlToStream(data, os, task)) {
                                editor.commit();
                            } else {
                                editor.abort();
                            }
                        }
                    }
                    snapshot = mHttpDiskCache.get(key);
                }
                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();

                    // Add by liulin
                    //copyStreamToLocalImage(data, fileInputStream, task);
                    //fileInputStream.reset();
                }
            } catch (IOException e) {
                LogUtil.e(TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                LogUtil.e(TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache());
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }
    return bitmap;
}

From source file:usbong.android.likha_collection_1.UsbongDecisionTreeEngineActivity.java

public void processPlayBGMusic() {
    try {/*  ww  w  .ja  v a 2s.  c om*/
        String newCurrUsbongBGAudioString = UsbongUtils
                .getBGAudioFilePathForThisScreenIfAvailable(currUsbongNode);
        Log.d(">>>>newCurrUsbongBGAudioString: ", "" + newCurrUsbongBGAudioString);
        Log.d(">>>>currUsbongBGAudioString: ", "" + currUsbongBGAudioString);

        if (currUsbongBGAudioString == newCurrUsbongBGAudioString) {
            return;
        } else {
            Log.d(">>>>", "inside currUsbongBGAudioString!=newCurrUsbongBGAudioString");
            currUsbongBGAudioString = newCurrUsbongBGAudioString;
            //            myBGMediaPlayer.stop();

            String filePath = UsbongUtils.getBGAudioFilePathFromUTree(currUsbongBGAudioString);
            //         Log.d(">>>>filePath: ",filePath);
            if (filePath != null) {
                Log.d(">>>>", "inside filePath!=null");
                Log.d(">>>>filePath: ", filePath);
                if (myBGMediaPlayer.isPlaying()) {
                    myBGMediaPlayer.stop();
                }
                myBGMediaPlayer.reset();
                //edited by Mike, 20151201
                //               myBGMediaPlayer.setDataSource(filePath);
                FileInputStream fis = new FileInputStream(new File(filePath));
                myBGMediaPlayer.setDataSource(fis.getFD());
                fis.close();

                myBGMediaPlayer.prepare();
                //            myMediaPlayer.setVolume(1.0f, 1.0f);
                myBGMediaPlayer.setLooping(true);
                myBGMediaPlayer.start();
                //            myMediaPlayer.seekTo(0);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:usbong.android.likha_collection_1.UsbongDecisionTreeEngineActivity.java

public void processSpeak(StringBuffer sb) {
    if (mTts.isSpeaking()) { //commented out by Mike, 24 Sept. 2015
        mTts.stop();//from  ww w . j  ava2 s  .  co  m
    }

    //      Log.d(">>>>currScreen",currScreen+"");
    switch (currScreen) {
    //edit later, Mike, Sept. 26, 2013
    case UsbongConstants.SIMPLE_ENCRYPT_SCREEN:
        break;
    //edit later, Mike, May 23, 2013
    case UsbongConstants.DCAT_SUMMARY_SCREEN:
        break;

    case UsbongConstants.LINK_SCREEN:
    case UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN:
    case UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        int totalRadioButtonsInContainer = radioButtonsContainer.size();
        for (int i = 0; i < totalRadioButtonsInContainer; i++) {
            sb.append(((RadioButton) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    new RadioButton(this), UsbongUtils.IS_RADIOBUTTON, radioButtonsContainer.elementAt(i)))
                            .getText().toString()
                    + ". ");
        }
        break;
    case UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        int totalCheckBoxesInContainer = checkBoxesContainer.size();
        for (int i = 0; i < totalCheckBoxesInContainer; i++) {
            sb.append(((CheckBox) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    new CheckBox(this), UsbongUtils.IS_CHECKBOX, checkBoxesContainer.elementAt(i))).getText()
                            .toString()
                    + ". ");
        }
        break;
    case UsbongConstants.AUDIO_RECORD_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        Button recordButton = (Button) findViewById(R.id.record_button);
        Button stopButton = (Button) findViewById(R.id.stop_button);
        Button playButton = (Button) findViewById(R.id.play_button);

        sb.append(recordButton.getText() + ". ");
        sb.append(stopButton.getText() + ". ");
        sb.append(playButton.getText() + ". ");
        break;
    case UsbongConstants.PAINT_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        Button paintButton = (Button) findViewById(R.id.paint_button);
        sb.append(paintButton.getText() + ". ");
        break;
    case UsbongConstants.PHOTO_CAPTURE_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        Button photoCaptureButton = (Button) findViewById(R.id.photo_capture_button);
        sb.append(photoCaptureButton.getText() + ". ");
        break;
    case UsbongConstants.TEXTFIELD_SCREEN:
    case UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN:
    case UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN:
    case UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN:
    case UsbongConstants.TEXTAREA_SCREEN:
    case UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");
        break;
    case UsbongConstants.CLASSIFICATION_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        int totalClassificationsInContainer = classificationContainer.size();
        for (int i = 0; i < totalClassificationsInContainer; i++) {
            sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    new TextView(this), UsbongUtils.IS_TEXTVIEW, classificationContainer.elementAt(i)))
                            .getText().toString()
                    + ". ");
        }
        break;
    case UsbongConstants.DATE_SCREEN:
    case UsbongConstants.TEXT_DISPLAY_SCREEN:
    case UsbongConstants.TEXT_IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.IMAGE_TEXT_DISPLAY_SCREEN:
    case UsbongConstants.CLICKABLE_IMAGE_TEXT_DISPLAY_SCREEN:
    case UsbongConstants.TEXT_CLICKABLE_IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.GPS_LOCATION_SCREEN:
    case UsbongConstants.QR_CODE_READER_SCREEN:
    case UsbongConstants.TIMESTAMP_DISPLAY_SCREEN:
    case UsbongConstants.VIDEO_FROM_FILE_WITH_TEXT_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");
        //              Log.d(">>>>sb",sb.toString());
        break;
    case UsbongConstants.CLICKABLE_IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.VIDEO_FROM_FILE_SCREEN:
        break;
    case UsbongConstants.YES_NO_DECISION_SCREEN:
    case UsbongConstants.SEND_TO_WEBSERVER_SCREEN:
    case UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");
        sb.append(yesStringValue + ". ");
        sb.append(noStringValue + ". ");
        break;
    /*                  
             case UsbongConstants.PAINT_SCREEN:
     if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_FILIPINO) {
       sb.append((String) getResources().getText(R.string.UsbongPaintScreenTextViewFILIPINO));
     }
     else if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_JAPANESE) {
       sb.append((String) getResources().getText(R.string.UsbongPaintScreenTextViewJAPANESE));                                            
     }
     else { //if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
       sb.append((String) getResources().getText(R.string.UsbongPaintScreenTextViewENGLISH));                                            
     }
     break;          
    */
    /*         //commented out by Mike, 20160213           
    case UsbongConstants.END_STATE_SCREEN:
        if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_FILIPINO) {
          sb.append((String) getResources().getText(R.string.UsbongEndStateTextViewFILIPINO));                      
        }
        else if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_JAPANESE) {
          sb.append((String) getResources().getText(R.string.UsbongEndStateTextViewJAPANESE));                                            
        }
        else { //if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
          sb.append((String) getResources().getText(R.string.UsbongEndStateTextViewENGLISH));                                            
        }
        break;          
       */
    }
    //edited by Mike, 21 July 2015
    try {

        currUsbongAudioString = UsbongUtils.getAudioFilePathForThisScreenIfAvailable(currUsbongNode);

        Log.d(">>>>currUsbongAudioString: ", "" + currUsbongAudioString);
        Log.d(">>>>currLanguageBeingUsed: ", UsbongUtils.getLanguageBasedOnID(currLanguageBeingUsed));

        //added by Mike, 2 Oct. 2015
        //exception for Mandarin
        //make simplified and traditional refer to the same audio folder
        if ((currLanguageBeingUsed == UsbongUtils.LANGUAGE_MANDARIN_SIMPLIFIED)
                || (currLanguageBeingUsed == UsbongUtils.LANGUAGE_MANDARIN_TRADITIONAL)) {
            currLanguageBeingUsed = UsbongUtils.LANGUAGE_MANDARIN;
        }

        String filePath = UsbongUtils.getAudioFilePathFromUTree(currUsbongAudioString,
                UsbongUtils.getLanguageBasedOnID(currLanguageBeingUsed));
        //         Log.d(">>>>filePath: ",filePath);
        if (filePath != null) {
            Log.d(">>>>", "inside filePath!=null");
            Log.d(">>>>filePath: ", filePath);
            if (myMediaPlayer.isPlaying()) {
                myMediaPlayer.stop();
            }
            myMediaPlayer.reset();
            //edited by Mike, 20151201
            //            myMediaPlayer.setDataSource(filePath);
            FileInputStream fis = new FileInputStream(new File(filePath));
            myMediaPlayer.setDataSource(fis.getFD());
            fis.close();

            myMediaPlayer.prepare();
            //            myMediaPlayer.setVolume(1.0f, 1.0f);
            myMediaPlayer.start();
            //            myMediaPlayer.seekTo(0);

            //added by Mike, 20160417
            myMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    if ((UsbongUtils.IS_IN_AUTO_PLAY_MODE) && (UsbongUtils.isAnAutoPlayException(instance))) {
                        processNextButtonPressed();
                    }
                }
            });
        } else {
            //it's either com.svox.pico (default) or com.svox.classic (Japanese, etc)                    
            //commented out by Mike, 11 Oct. 2015
            //            mTts.setEngineByPackageName("com.svox.pico"); //note: this method is already deprecated

            //20160417
            mTtsParams = new HashMap<String, String>();
            mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, UsbongConstants.MY_UTTERANCE_ID);

            switch (currLanguageBeingUsed) {
            case UsbongUtils.LANGUAGE_FILIPINO:
                mTts.setLanguage(new Locale("spa", "ESP"));
                if (Build.VERSION.RELEASE.startsWith("5")) {
                    mTts.speak(UsbongUtils.convertFilipinoToSpanishAccentFriendlyText(sb.toString()),
                            TextToSpeech.QUEUE_FLUSH, null, null); //QUEUE_ADD         
                } else {
                    mTts.speak(UsbongUtils.convertFilipinoToSpanishAccentFriendlyText(sb.toString()),
                            TextToSpeech.QUEUE_FLUSH, null); //QUEUE_ADD                              
                }
                break;
            case UsbongUtils.LANGUAGE_JAPANESE:
                //                  commented out by Mike, 11 Oct. 2015
                //                  mTts.setEngineByPackageName("com.svox.classic"); //note: this method is already deprecated
                mTts.setLanguage(new Locale("ja", "JP"));
                if (Build.VERSION.RELEASE.startsWith("5")) {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null, null); //QUEUE_ADD         

                } else {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null); //QUEUE_ADD         
                }
                break;
            case UsbongUtils.LANGUAGE_ENGLISH:
                mTts.setLanguage(new Locale("en", "US"));
                if (Build.VERSION.RELEASE.startsWith("5")) {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null, null); //QUEUE_ADD         
                } else {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null); //QUEUE_ADD                              
                }
                break;
            default:
                mTts.setLanguage(new Locale("en", "US"));
                mTts.speak(sb.toString(), TextToSpeech.QUEUE_ADD, null); //QUEUE_FLUSH         
                break;
            }

            //added by Mike, 20160417
            mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                @Override
                public void onDone(String utteranceId) {
                    if (utteranceId.equals(UsbongConstants.MY_UTTERANCE_ID)) {
                        //added by Mike, 20160608
                        if ((UsbongUtils.IS_IN_AUTO_PLAY_MODE)
                                && (UsbongUtils.isAnAutoPlayException(instance))) {
                            instance.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    processNextButtonPressed();
                                }
                            });
                        }
                    }
                }

                @Override
                @Deprecated
                public void onError(String utteranceId) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onStart(String utteranceId) {
                    // TODO Auto-generated method stub                  
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.aimfire.demo.CamcorderActivity.java

private void generateThumbAndPreview(String filePath) {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "generateThumbAndPreview");

    String movieNameNoExt = MediaScanner.getMovieNameNoExt(filePath);
    String previewPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpeg";
    String thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpg";

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmap = null;//  www.j  a  va 2s.co m

    try {
        FileInputStream inputStream = new FileInputStream(filePath);
        retriever.setDataSource(inputStream.getFD());
        inputStream.close();

        bitmap = retriever.getFrameAtTime(0L, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        retriever.release();

        if (bitmap != null) {
            FileOutputStream out = null;
            out = new FileOutputStream(previewPath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
            out.close();

            Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, MainConsts.THUMBNAIL_SIZE,
                    MainConsts.THUMBNAIL_SIZE);
            out = new FileOutputStream(thumbPath);
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.close();
        }
    } catch (Exception e) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "generateThumbAndPreview: exception" + e.getMessage());
        retriever.release();
        FirebaseCrash.report(e);
    }
}

From source file:usbong.android.retrocc.UsbongDecisionTreeEngineActivity.java

public void processSpeak(StringBuffer sb) {
    if (mTts.isSpeaking()) { //commented out by Mike, 24 Sept. 2015
        mTts.stop();/*from  w w w . j  a  v  a2  s  . c om*/
    }

    //      Log.d(">>>>currScreen",currScreen+"");
    switch (currScreen) {
    //edit later, Mike, Sept. 26, 2013
    case UsbongConstants.SIMPLE_ENCRYPT_SCREEN:
        break;
    //edit later, Mike, May 23, 2013
    case UsbongConstants.DCAT_SUMMARY_SCREEN:
        break;

    case UsbongConstants.LINK_SCREEN:
    case UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN:
    case UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        int totalRadioButtonsInContainer = radioButtonsContainer.size();
        for (int i = 0; i < totalRadioButtonsInContainer; i++) {
            sb.append(((RadioButton) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    new RadioButton(this), UsbongUtils.IS_RADIOBUTTON, radioButtonsContainer.elementAt(i)))
                            .getText().toString()
                    + ". ");
        }
        break;
    case UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        int totalCheckBoxesInContainer = checkBoxesContainer.size();
        for (int i = 0; i < totalCheckBoxesInContainer; i++) {
            sb.append(((CheckBox) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    new CheckBox(this), UsbongUtils.IS_CHECKBOX, checkBoxesContainer.elementAt(i))).getText()
                            .toString()
                    + ". ");
        }
        break;
    case UsbongConstants.AUDIO_RECORD_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        Button recordButton = (Button) findViewById(R.id.record_button);
        Button stopButton = (Button) findViewById(R.id.stop_button);
        Button playButton = (Button) findViewById(R.id.play_button);

        sb.append(recordButton.getText() + ". ");
        sb.append(stopButton.getText() + ". ");
        sb.append(playButton.getText() + ". ");
        break;
    case UsbongConstants.PAINT_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        Button paintButton = (Button) findViewById(R.id.paint_button);
        sb.append(paintButton.getText() + ". ");
        break;
    case UsbongConstants.PHOTO_CAPTURE_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        Button photoCaptureButton = (Button) findViewById(R.id.photo_capture_button);
        sb.append(photoCaptureButton.getText() + ". ");
        break;
    case UsbongConstants.TEXTFIELD_SCREEN:
    case UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN:
    case UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN:
    case UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN:
    case UsbongConstants.TEXTAREA_SCREEN:
    case UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");
        break;
    case UsbongConstants.CLASSIFICATION_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");

        int totalClassificationsInContainer = classificationContainer.size();
        for (int i = 0; i < totalClassificationsInContainer; i++) {
            sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    new TextView(this), UsbongUtils.IS_TEXTVIEW, classificationContainer.elementAt(i)))
                            .getText().toString()
                    + ". ");
        }
        break;
    case UsbongConstants.DATE_SCREEN:
    case UsbongConstants.TEXT_DISPLAY_SCREEN:
    case UsbongConstants.TEXT_IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.IMAGE_TEXT_DISPLAY_SCREEN:
    case UsbongConstants.CLICKABLE_IMAGE_TEXT_DISPLAY_SCREEN:
    case UsbongConstants.TEXT_CLICKABLE_IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.GPS_LOCATION_SCREEN:
    case UsbongConstants.QR_CODE_READER_SCREEN:
    case UsbongConstants.TIMESTAMP_DISPLAY_SCREEN:
    case UsbongConstants.VIDEO_FROM_FILE_WITH_TEXT_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");
        //              Log.d(">>>>sb",sb.toString());
        break;
    case UsbongConstants.CLICKABLE_IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.IMAGE_DISPLAY_SCREEN:
    case UsbongConstants.VIDEO_FROM_FILE_SCREEN:
        break;
    case UsbongConstants.YES_NO_DECISION_SCREEN:
    case UsbongConstants.SEND_TO_WEBSERVER_SCREEN:
    case UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN:
        sb.append(((TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                new TextView(this), UsbongUtils.IS_TEXTVIEW, currUsbongNode)).getText().toString() + ". ");
        sb.append(yesStringValue + ". ");
        sb.append(noStringValue + ". ");
        break;
    /*                  
             case UsbongConstants.PAINT_SCREEN:
     if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_FILIPINO) {
       sb.append((String) getResources().getText(R.string.UsbongPaintScreenTextViewFILIPINO));
     }
     else if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_JAPANESE) {
       sb.append((String) getResources().getText(R.string.UsbongPaintScreenTextViewJAPANESE));                                            
     }
     else { //if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
       sb.append((String) getResources().getText(R.string.UsbongPaintScreenTextViewENGLISH));                                            
     }
     break;          
    */
    /*         //commented out by Mike, 20160213           
    case UsbongConstants.END_STATE_SCREEN:
        if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_FILIPINO) {
          sb.append((String) getResources().getText(R.string.UsbongEndStateTextViewFILIPINO));                      
        }
        else if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_JAPANESE) {
          sb.append((String) getResources().getText(R.string.UsbongEndStateTextViewJAPANESE));                                            
        }
        else { //if (currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
          sb.append((String) getResources().getText(R.string.UsbongEndStateTextViewENGLISH));                                            
        }
        break;          
       */
    }
    //edited by Mike, 21 July 2015
    try {

        currUsbongAudioString = UsbongUtils.getAudioFilePathForThisScreenIfAvailable(currUsbongNode);

        Log.d(">>>>currUsbongAudioString: ", "" + currUsbongAudioString);
        Log.d(">>>>currLanguageBeingUsed: ", UsbongUtils.getLanguageBasedOnID(currLanguageBeingUsed));

        //added by Mike, 2 Oct. 2015
        //exception for Mandarin
        //make simplified and traditional refer to the same audio folder
        if ((currLanguageBeingUsed == UsbongUtils.LANGUAGE_MANDARIN_SIMPLIFIED)
                || (currLanguageBeingUsed == UsbongUtils.LANGUAGE_MANDARIN_TRADITIONAL)) {
            currLanguageBeingUsed = UsbongUtils.LANGUAGE_MANDARIN;
        }

        String filePath = UsbongUtils.getAudioFilePathFromUTree(currUsbongAudioString,
                UsbongUtils.getLanguageBasedOnID(currLanguageBeingUsed));
        //         Log.d(">>>>filePath: ",filePath);
        if (filePath != null) {
            Log.d(">>>>", "inside filePath!=null");
            Log.d(">>>>filePath: ", filePath);
            if (myMediaPlayer.isPlaying()) {
                myMediaPlayer.stop();
            }
            myMediaPlayer.reset();
            //edited by Mike, 20151201
            //            myMediaPlayer.setDataSource(filePath);
            FileInputStream fis = new FileInputStream(new File(filePath));
            myMediaPlayer.setDataSource(fis.getFD());
            fis.close();

            myMediaPlayer.prepare();
            //            myMediaPlayer.setVolume(1.0f, 1.0f);
            myMediaPlayer.start();
            //            myMediaPlayer.seekTo(0);

            //added by Mike, 20160417
            myMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    if (UsbongUtils.IS_IN_AUTO_PLAY_MODE) {
                        processNextButtonPressed();
                    }
                }
            });
        } else {
            //it's either com.svox.pico (default) or com.svox.classic (Japanese, etc)                    
            //commented out by Mike, 11 Oct. 2015
            //            mTts.setEngineByPackageName("com.svox.pico"); //note: this method is already deprecated

            //20160417
            mTtsParams = new HashMap<String, String>();
            mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, UsbongConstants.MY_UTTERANCE_ID);

            switch (currLanguageBeingUsed) {
            case UsbongUtils.LANGUAGE_FILIPINO:
                mTts.setLanguage(new Locale("spa", "ESP"));
                if (Build.VERSION.RELEASE.startsWith("5")) {
                    mTts.speak(UsbongUtils.convertFilipinoToSpanishAccentFriendlyText(sb.toString()),
                            TextToSpeech.QUEUE_FLUSH, null, null); //QUEUE_ADD         
                } else {
                    mTts.speak(UsbongUtils.convertFilipinoToSpanishAccentFriendlyText(sb.toString()),
                            TextToSpeech.QUEUE_FLUSH, null); //QUEUE_ADD                              
                }
                break;
            case UsbongUtils.LANGUAGE_JAPANESE:
                //                  commented out by Mike, 11 Oct. 2015
                //                  mTts.setEngineByPackageName("com.svox.classic"); //note: this method is already deprecated
                mTts.setLanguage(new Locale("ja", "JP"));
                if (Build.VERSION.RELEASE.startsWith("5")) {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null, null); //QUEUE_ADD         

                } else {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null); //QUEUE_ADD         
                }
                break;
            case UsbongUtils.LANGUAGE_ENGLISH:
                mTts.setLanguage(new Locale("en", "US"));
                if (Build.VERSION.RELEASE.startsWith("5")) {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null, null); //QUEUE_ADD         
                } else {
                    mTts.speak(sb.toString(), TextToSpeech.QUEUE_FLUSH, null); //QUEUE_ADD                              
                }
                break;
            default:
                mTts.setLanguage(new Locale("en", "US"));
                mTts.speak(sb.toString(), TextToSpeech.QUEUE_ADD, null); //QUEUE_FLUSH         
                break;
            }

            //added by Mike, 20160417
            mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                @Override
                public void onDone(String utteranceId) {
                    if (utteranceId.equals(UsbongConstants.MY_UTTERANCE_ID)) {
                        if (UsbongUtils.IS_IN_AUTO_PLAY_MODE) {
                            instance.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    processNextButtonPressed();
                                }
                            });
                        }
                    }
                }

                @Override
                @Deprecated
                public void onError(String utteranceId) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onStart(String utteranceId) {
                    // TODO Auto-generated method stub                  
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc/*w  ww  .j  a v a  2s  .  c om*/
 */
@Override
public Media createMedia(final String uri, boolean isVideo, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    if (!uri.startsWith(FileSystemStorage.getInstance().getAppHomePath())) {
        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;
}