您能举例说明如何将最后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
非常感谢,找不到我需要的信息,我真的在搜索。
答案 0 :(得分:0)
试试此代码
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); }
}
}
答案 1 :(得分:0)
这是一个适合我的例子:
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();