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:de.haber.xmind2latex.XMindToLatexExporterConfigurationTest.java

@Test
public void testConfigureIn2() {
    File in = new File("src/test/resources/content.xml");

    String expectedOut = in.getAbsolutePath().concat(".tex");
    String[] args = new String[] { "--input", in.getPath() };
    XMindToLatexExporter exporter;//from  ww  w  .  jav  a 2  s  .  c o  m
    try {
        exporter = CliParameters.build(args);

        assertEquals(expectedOut, exporter.getTargetFile().getAbsolutePath());
        FileInputStream fis = (FileInputStream) exporter.getxMindSourceAsStream();
        assertTrue(fis.getFD().valid());
        assertFalse(exporter.isOverwriteExistingFile());
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:de.haber.xmind2latex.XMindToLatexExporterConfigurationTest.java

@Test
public void testConfigureIn() {
    File in = new File("src/test/resources/content.xml");

    String expectedOut = in.getAbsolutePath().concat(".tex");

    String[] args = new String[] { "-i", in.getPath() };
    XMindToLatexExporter exporter;/*from   w  ww  . ja  v a  2 s. co  m*/
    try {
        exporter = CliParameters.build(args);

        assertEquals(expectedOut, exporter.getTargetFile().getAbsolutePath());
        assertTrue(exporter.getxMindSourceAsStream() instanceof FileInputStream);
        FileInputStream fis = (FileInputStream) exporter.getxMindSourceAsStream();
        assertTrue(fis.getFD().valid());
        assertFalse(exporter.isOverwriteExistingFile());
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * 3GP??Video?Audio??.//  w w  w  .j  a  va  2  s.co m
 * 
 * @param mFile ???URI
 * @return Video?true, audio?false
 */
public static boolean checkVideo(final File mFile) {
    int height = 0;
    try {
        mMediaPlayer = new MediaPlayer();
        FileInputStream fis = null;
        FileDescriptor mFd = null;

        fis = new FileInputStream(mFile);
        mFd = fis.getFD();

        mMediaPlayer.setDataSource(mFd);
        mMediaPlayer.prepare();
        height = mMediaPlayer.getVideoHeight();
        mMediaPlayer.release();
        fis.close();
    } catch (Exception e) {
        if (BuildConfig.DEBUG) {
            e.printStackTrace();
        }
    }

    return height > 0;
}

From source file:com.intel.xdk.player.Player.java

public void startAudio(String strRelativeFileURL, boolean shouldLoop) {
    if (isPlayingPodcast()) {
        injectJS(/*  w  w  w. jav  a2  s  .  c o  m*/
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.busy',true,true);document.dispatchEvent(ev);");
        return;
    } else if (isPlayingAudio()) {
        stopAudio();
    }

    soundName = strRelativeFileURL;
    Object path = pathToFile(strRelativeFileURL);

    try {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
        } catch (Exception e) {
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setLooping(shouldLoop);
        mediaPlayer.setOnErrorListener(soundOnError);
        mediaPlayer.setOnCompletionListener(soundOnComplete);

        //set data source based on type
        if (path instanceof AssetFileDescriptor) {
            try {
                AssetFileDescriptor afd = ((AssetFileDescriptor) path);
                mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            File file = new File((String) path);
            try {
                FileInputStream fis = new FileInputStream(file);
                mediaPlayer.setDataSource(fis.getFD());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        mediaPlayer.prepare();
        mediaPlayer.seekTo(audioTime);
        mediaPlayer.setVolume(audioVolume, audioVolume);
        mediaPlayer.start();
    } catch (Exception e) {
        injectJS(
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.error',true,true);document.dispatchEvent(ev);");
        return;
    }

    //activity.trackPageView("/intel.xdk.podcast." + getAudioName(soundName) + ".stop");

    setPlayingAudio(true);
    injectJS(
            "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.start');document.dispatchEvent(ev);");
}

From source file:com.commontime.cordova.audio.AudioPlayer.java

/**
 * load audio file//from w  ww  .  j a  v a  2 s .  co  m
 * @throws IOException
 * @throws IllegalStateException
 * @throws SecurityException
 * @throws IllegalArgumentException
 */
private void loadAudioFile(String file)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
    if (this.isStreaming(file)) {
        this.player.setDataSource(file);
        this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //if it's a streaming file, play mode is implied
        this.setMode(MODE.PLAY);
        this.setState(STATE.MEDIA_STARTING);
        this.player.setOnPreparedListener(this);
        this.player.prepareAsync();
    } else {
        if (file.startsWith("/android_asset/")) {
            String f = file.substring(15);
            android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets()
                    .openFd(f);
            this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
        } else {
            File fp = new File(file);
            if (fp.exists()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                this.player.setDataSource(fileInputStream.getFD());
                fileInputStream.close();
            } else {
                this.player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/" + file);
            }
        }
        this.setState(STATE.MEDIA_STARTING);
        this.player.setOnPreparedListener(this);
        this.player.prepare();

        // Get duration
        this.duration = getDurationInSeconds();
    }
}

From source file:fm.smart.r1.activity.CreateSoundActivity.java

public void onClick(View v) {
    String threegpfile_name = "test.3gp_amr";
    String amrfile_name = "test.amr";
    File dir = this.getDir("sounds", MODE_WORLD_READABLE);
    final File threegpfile = new File(dir, threegpfile_name);
    File amrfile = new File(dir, amrfile_name);
    String path = threegpfile.getAbsolutePath();
    Log.d("CreateSoundActivity", path);
    Log.d("CreateSoundActivity", (String) button.getText());
    if (button.getText().equals("Start")) {
        try {/*from  w  w  w .jav a 2s.  com*/
            recorder = new MediaRecorder();

            // ContentValues values = new ContentValues(3);
            //
            // values.put(MediaStore.MediaColumns.TITLE, "test");
            // values.put(MediaStore.MediaColumns.DATE_ADDED,
            // System.currentTimeMillis());
            // values.put(MediaStore.MediaColumns.MIME_TYPE,
            // MediaRecorder.OutputFormat.THREE_GPP);
            //             
            // ContentResolver contentResolver = new ContentResolver(this);
            //             
            // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
            // Uri newUri = contentResolver.insert(base, values);

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

            recorder.prepare();
            button.setText("Stop");
            recorder.start();
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    } else {
        FileOutputStream os = null;
        FileInputStream is = null;
        try {
            recorder.stop();
            recorder.release(); // Now the object cannot be reused
            button.setEnabled(false);

            // ThreegpReader tr = new ThreegpReader(threegpfile);
            // os = new FileOutputStream(amrfile);
            // tr.extractAmr(os);
            is = new FileInputStream(threegpfile);
            playSound(is.getFD());

            final String media_entity = "http://test.com/test.mp3";
            final String author = "tansaku";
            final String author_url = "http://smart.fm/users/tansaku";

            if (Main.isNotLoggedIn(this)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName(this, LoginActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                LoginActivity.return_to = CreateSoundActivity.class.getName();
                LoginActivity.params = new HashMap<String, String>();
                LoginActivity.params.put("item_id", item_id);
                LoginActivity.params.put("list_id", list_id);
                LoginActivity.params.put("id", id);
                LoginActivity.params.put("to_record", to_record);
                LoginActivity.params.put("sound_type", sound_type);
                startActivity(intent);
            } else {

                final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
                myOtherProgressDialog.setTitle("Please Wait ...");
                myOtherProgressDialog.setMessage("Creating Sound ...");
                myOtherProgressDialog.setIndeterminate(true);
                myOtherProgressDialog.setCancelable(true);

                final Thread create_sound = new Thread() {
                    public void run() {
                        // TODO make this interruptable .../*if
                        // (!this.isInterrupted())*/
                        CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author,
                                author_url, "1", id);

                        myOtherProgressDialog.dismiss();

                    }
                };
                myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        create_sound.interrupt();
                    }
                });
                OnCancelListener ocl = new OnCancelListener() {
                    public void onCancel(DialogInterface arg0) {
                        create_sound.interrupt();
                    }
                };
                myOtherProgressDialog.setOnCancelListener(ocl);
                myOtherProgressDialog.show();
                create_sound.start();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

From source file:fm.smart.r1.CreateSoundActivity.java

public void onClick(View v) {
    String threegpfile_name = "test.3gp_amr";
    String amrfile_name = "test.amr";
    File dir = this.getDir("sounds", MODE_WORLD_READABLE);
    final File threegpfile = new File(dir, threegpfile_name);
    File amrfile = new File(dir, amrfile_name);
    String path = threegpfile.getAbsolutePath();
    Log.d("CreateSoundActivity", path);
    Log.d("CreateSoundActivity", (String) button.getText());
    if (button.getText().equals("Start")) {
        try {//  w  w w.  ja va 2 s  . com
            recorder = new MediaRecorder();

            // ContentValues values = new ContentValues(3);
            //
            // values.put(MediaStore.MediaColumns.TITLE, "test");
            // values.put(MediaStore.MediaColumns.DATE_ADDED,
            // System.currentTimeMillis());
            // values.put(MediaStore.MediaColumns.MIME_TYPE,
            // MediaRecorder.OutputFormat.THREE_GPP);
            //
            // ContentResolver contentResolver = new ContentResolver(this);
            //
            // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
            // Uri newUri = contentResolver.insert(base, values);

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

            recorder.prepare();
            button.setText("Stop");
            recorder.start();
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    } else {
        FileOutputStream os = null;
        FileInputStream is = null;
        try {
            recorder.stop();
            recorder.release(); // Now the object cannot be reused
            button.setEnabled(false);

            // ThreegpReader tr = new ThreegpReader(threegpfile);
            // os = new FileOutputStream(amrfile);
            // tr.extractAmr(os);
            is = new FileInputStream(threegpfile);
            playSound(is.getFD());

            final String media_entity = "http://test.com/test.mp3";
            final String author = "tansaku";
            final String author_url = "http://smart.fm/users/tansaku";

            if (LoginActivity.isNotLoggedIn(this)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName(this, LoginActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                LoginActivity.return_to = CreateSoundActivity.class.getName();
                LoginActivity.params = new HashMap<String, String>();
                LoginActivity.params.put("item_id", item_id);
                LoginActivity.params.put("goal_id", goal_id);
                LoginActivity.params.put("id", id);
                LoginActivity.params.put("to_record", to_record);
                LoginActivity.params.put("sound_type", sound_type);
                startActivity(intent);
            } else {

                final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
                myOtherProgressDialog.setTitle("Please Wait ...");
                myOtherProgressDialog.setMessage("Creating Sound ...");
                myOtherProgressDialog.setIndeterminate(true);
                myOtherProgressDialog.setCancelable(true);

                final Thread create_sound = new Thread() {
                    public void run() {
                        // TODO make this interruptable .../*if
                        // (!this.isInterrupted())*/
                        CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author,
                                author_url, "1", item_id, id, to_record);
                        // this will also ensure item is in goal, but this
                        // should be sentence
                        // submission if we are handling sentence sound.
                        if (sound_type.equals(Integer.toString(R.id.cue_sound))) {
                            CreateSoundActivity.add_item_result = new AddItemResult(
                                    Main.lookup.addItemToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, CreateSoundActivity.create_sound_result.sound_id));
                        } else {
                            // ensure item is in goal
                            CreateSoundActivity.add_item_result = new AddItemResult(Main.lookup
                                    .addItemToGoal(Main.transport, Main.default_study_goal_id, item_id, null));
                            CreateSoundActivity.add_sentence_result = new AddSentenceResult(
                                    Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, id, CreateSoundActivity.create_sound_result.sound_id));

                        }
                        myOtherProgressDialog.dismiss();

                    }
                };
                myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        create_sound.interrupt();
                    }
                });
                OnCancelListener ocl = new OnCancelListener() {
                    public void onCancel(DialogInterface arg0) {
                        create_sound.interrupt();
                    }
                };
                myOtherProgressDialog.setOnCancelListener(ocl);
                myOtherProgressDialog.show();
                create_sound.start();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

From source file:brama.com.hearthum.waveform.WaveformFragment.java

protected synchronized void onPlay(int startPosition) {
    if (mIsPlaying) {
        handlePause();/*from w w  w  . j  ava  2  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 (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) {
                Log.e(TAG, "Exception trying to play file subset", e);
                mPlayer.reset();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(mFile.getAbsolutePath());
                mPlayer.prepare();
                mPlayStartOffset = 0;
            }
        }

        mPlayer.setOnCompletionListener((MediaPlayer mediaPlayer) -> handlePause());
        mIsPlaying = true;

        if (mPlayStartOffset == 0) {
            mPlayer.seekTo(mPlayStartMsec);
        }
        mPlayer.start();
        updateDisplay();
        enableDisableButtons();
    } catch (Exception e) {
        Log.e(TAG, "Exception while playing file", e);
    }
}

From source file:example.audiovisualization.app.fragment.WaveformFragment.java

protected synchronized void onPlay(int startPosition) {
    if (mIsPlaying) {
        handlePause();/*from   w  w w. ja v a2  s .co 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 (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) {
                Log.e(TAG, "Exception trying to play file subset", e);
                mPlayer.reset();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(mFile.getAbsolutePath());
                mPlayer.prepare();
                mPlayStartOffset = 0;
            }
        }

        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                WaveformFragment.this.handlePause();
            }
        });
        mIsPlaying = true;

        if (mPlayStartOffset == 0) {
            mPlayer.seekTo(mPlayStartMsec);
        }
        mPlayer.start();
        updateDisplay();
        enableDisableButtons();
    } catch (Exception e) {
        Log.e(TAG, "Exception while playing file", e);
    }
}

From source file:ac.robinson.paperchains.PaperChainsActivity.java

private void streamAudio(String audioPath) {
    resetAudioPlayer();//ww w.  j ava  2 s  .c  o  m

    mPlayButton.setVisibility(View.VISIBLE); // undo invisible by resetAudioPlayer();
    mPlayButton.setImageResource(R.drawable.ic_refresh_white_24dp);
    mPlayButton.startAnimation(mRotateAnimation);

    mAudioPlayer = new MediaPlayer();
    mAudioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        try {
            // slightly hacky way of detecting whether the path is a url or a file, and handling appropriately
            new URL(audioPath); // only for the exception it throws
            mAudioPlayer.setDataSource(audioPath);
        } catch (MalformedURLException e) {
            FileInputStream inputStream = new FileInputStream(audioPath);
            mAudioPlayer.setDataSource(inputStream.getFD());
            inputStream.close();
        }
        mAudioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                mPlayButton.clearAnimation();
                mPlayButton.setImageResource(R.drawable.ic_pause_white_24dp);
            }
        });
        mAudioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mPlayButton.clearAnimation();
                mPlayButton.setImageResource(R.drawable.ic_play_arrow_white_24dp);
            }
        });
        mAudioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                streamAudioLoadFailed(R.string.hint_soundcloud_load_failed);
                return true;
            }
        });
        mAudioPlayer.prepareAsync();
    } catch (IOException e) {
        streamAudioLoadFailed(R.string.hint_soundcloud_load_failed);
    }
}