如何从媒体文件中剪切最后一部分?

How to cut a last part from media file?

能否举例说明如何将最后 N 秒从一个音频文件复制到另一个文件。我使用下面的代码从麦克风写了一个演讲,但是我有这个记录的长度限制,但是我需要文件的最后一部分,因为它包含了文件开头很可能不包含的重要信息它。 当文件长度超过设置限制时我需要它只复制最后N秒。

    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

非常感谢,找不到我需要的信息,我真的搜索了。

试试这个代码

public void copyAudio(String sourceFileName, String destinationFileName,int lastNSeconds) {
AudioInputStream inputStream = null;
AudioInputStream shortenedStream = null;
try {
  File file = new File(sourceFileName);
  AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
  AudioFormat format = fileFormat.getFormat();
  long frames = audioInputStream.getFrameLength();
  double totalduration = (frames+0.0) / format.getFrameRate();  //returns the total duration of the audio
  inputStream = AudioSystem.getAudioInputStream(file);
  int bytesPerSecond = format.getFrameSize() * (int)format.getFrameRate();
  inputStream.skip((totalduration-lastNSeconds) * bytesPerSecond);
  long framesOfAudioToCopy = lastNSeconds * (int)format.getFrameRate();
  shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
  File destinationFile = new File(destinationFileName);
  AudioSystem.write(shortenedStream, fileFormat.getType(), destinationFile);
} catch (Exception e) {
  println(e);
} finally {
  if (inputStream != null) try { inputStream.close(); } catch (Exception e) { println(e); }
  if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { println(e); }
 }
}

这是一个适合我的例子:

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

打电话:

  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();