【小程式】切割和合並mp3檔案

weixin_33913377發表於2016-12-21

/* * 小程式:切割和合並mp3檔案 */

package com.michael.lin;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.SequenceInputStream;

import java.util.Enumeration;

import java.util.Vector;

public class Demo02 {

public static void main(String[] args) throws IOException{nifeMp3();mergeMp3();}

//1.切割mp3檔案

public static void nifeMp3() throws IOException {

//1.定位要切割的檔案

File mp3File = new File("c:\\music\\michael.mp3");

//2.定位切割檔案存放位置

File partsFile = new File("c:\\music\\parts\\");

//3.定位輸入通道

FileInputStream fileInputStream = new FileInputStream(mp3File);

byte[] buf = new byte[1024*1024];

int length = 0;

for(int i=0; (length=fileInputStream.read(buf))!=-1; i++){

File part = new File(partsFile, "part"+i+".mp3");

FileOutputStream fileOutputStream = new FileOutputStream(part);

fileOutputStream.write(buf,0,length);

fileOutputStream.close();}fileInputStream.close();

}

//2.合併mp3檔案

public static void mergeMp3() throws IOException{

//1.定位要和並的檔案的位置

File dir = new File("c:\\music\\parts\\");

//2.列出所有要合併的檔案存入序列流中

Vectorvector = new Vector();

File[] files = dir.listFiles();

for(File file: files){

if(file.toString().endsWith(".mp3")){

FileInputStream fileInputStream = new FileInputStream(file);

vector.add(fileInputStream);

}

}

//將檔案集合放入序列輸入流中

Enumerationenumeration = vector.elements();

SequenceInputStream sequenceInputStream = new SequenceInputStream(enumeration);

//3.開始和合並檔案

File michael = new File(dir,"michael.mp3");

FileOutputStream michaelOutput = new FileOutputStream(michael);

byte[] buf = new byte[1024];

int length  = 0;

while((length=sequenceInputStream.read(buf))!=-1){

michaelOutput.write(buf,0,length);

}

}

sequenceInputStream.close();

michaelOutput.close();

}

相關文章