Search code examples
javamicrophonespeech

How to cut a last part from media file?


Could you give an example of how to copy the last N second from an audio file to another file. I write a speech from the microphone using the code below, but I have a length limit for this record, but I need the last part of the file because it contains important information at the time when the beginning of the file most likely does not contain it. I need it when the file length exceeds the set limit copy only the last N seconds.

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
    String fileName = Environment.getExternalStorageDirectory() + "/record.mp3";
    recorder.setOutputFile(fileName);
    try {
        recorder.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    recorder.start();   // Recording is now started

Many thanks, could not find the information I needed, I really searched.


Solution

  • Here is an examples that works for me :

    compile 'com.googlecode.mp4parser:isoparser:1.1.21'
    

    Calling :

      AACTrackImpl aacTrack = new AACTrackImpl(new FileDataSourceImpl(RECORD));
                if (aacTrack.getSamples().size()>1000) {
                    CroppedTrack aacTrackShort = new CroppedTrack(aacTrack, aacTrack.getSamples().size() - 1000, aacTrack.getSamples().size());
                    Movie movie = new Movie();
                    movie.addTrack(aacTrackShort);
                    Container mp4file = new DefaultMp4Builder().build(movie);
                    FileChannel fc = new FileOutputStream(new File(fileName)).getChannel();
                    mp4file.writeContainer(fc);
                    fc.close();
                    aacTrackShort.close();
                    aacTrack.close();