Problème pour concatener deux MP3 en java

babylone78 Messages postés 8 Date d'inscription mardi 13 avril 2004 Statut Membre Dernière intervention 11 janvier 2011 - 21 déc. 2010 à 10:45
 Utilisateur anonyme - 22 déc. 2010 à 12:36
Hello,

je voudrais concatener deux fichiers mp3 en Java. J'ai trouvé ce bout de code sur le net qui fonctionne très bien avec deux fichiers wav. Pour que ca marche avec du mp3 j'ai installé le plug-in mp3 de tritonus tritonus. J'ai testé l'encodage mp3 et ca fonctionne mais pas moyen de concatener deux mp3.

import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

public class WavAppender {
    public static void main(String[] args) {
            String wavFile1 = "D:\\wav1.wav";
            String wavFile2 = "D:\\wav2.wav";

            try {
                    AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
                    AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));

                    AudioInputStream appendedFiles = 
                            new AudioInputStream(
                                new SequenceInputStream(clip1, clip2),     
                                clip1.getFormat(), 
                                clip1.getFrameLength() + clip2.getFrameLength());

                    AudioSystem.write(appendedFiles, 
                            AudioFileFormat.Type.WAVE, 
                            new File("D:\\wavAppended.wav"));
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }
}


voici ma fonction modifiée pour le mp3 :
private void concat(String mp3File1, String mp3File2, String mp3Resulat) {
AudioFileFormat.Type MP3 = AudioFileTypes.getType("MP3", "mp3");
            try {
                    AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(mp3File1));
                    AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(mp3File2));

                    AudioInputStream appendedFiles = 
                            new AudioInputStream(
                                new SequenceInputStream(clip1, clip2),     
                                clip1.getFormat(), 
                                clip1.getFrameLength() + clip2.getFrameLength());

                    AudioSystem.write(appendedFiles, 
                            MP3, 
                            new File(mp3Resulat));
                    appendedFiles.close();
                    clip1.close();
                    clip2.close();
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }

ca me renvoie une exception du type
java.lang.IllegalArgumentException: could not write audio file: file type not supported: MP3
at javax.sound.sampled.AudioSystem.write(Unknown Source)
at voicestream.audiolan.recorder.Mp3Appender.concat(Mp3Appender.java:126)
at voicestream.audiolan.recorder.Mp3Appender.run(Mp3Appender.java:82)
at java.lang.Thread.run(Unknown Source)


l'api sound est assez obscure pour moi alors si vous avez une idée....ou une autre solution à me proposer (en fait je veux encoder en MP3 à volée un flux audio PCM que je recupere sur le réseau).

Merci

5 réponses

Utilisateur anonyme
21 déc. 2010 à 15:12
Bonjour

Comment as-tu installé ce plug-in? JavaSound ne trouve pas le SPI capable de décoder/encoder du MP3 d'après le message d'erreur.















0
babylone78 Messages postés 8 Date d'inscription mardi 13 avril 2004 Statut Membre Dernière intervention 11 janvier 2011
21 déc. 2010 à 15:45
hello

je ne crois pas que ce soit fait sous la forme d'un SPI. Je travaille sous windows et
j'ai suivi la procédure indiquée dans le read me founi.
1 j'ai mis le fichier lametritonus.dll dans le repertoire de java jre\bin
2 j'ai mis les deux jars tritonus_mp3.jar et tritonus_share.mp3 dans le repertoire jre\lib\ext
3 j'ai mis le lame_enc.dll dans le repertoire windows\system32 (ca marche aussi si tu le met la où tu compiles des classes)

y a une procedure analogue decrite dans le fichier pour linux avec un fichier liblametritonus.so à la place de la DLL (etape 1)

si tu as un erreur avec un mallocI qq dans le message , c'est qu'il y a un fichier mal placé. j'ai un peu galéré au debut pour que ca fonctionne aussi
0
Utilisateur anonyme
21 déc. 2010 à 22:45
Appelle la méthode AudioSystem.isFileTypeSupported et tu verras... elle te renverra false. Moi non plus je n'ai rien vu en rapport avec les SPI sur cette page.

Voici un exemple d'utilisation de SPI pour le format MP3 :
http://www.javaworld.com/jw-11-2000/jw-1103-mp3.html?page=1

et cela rejoint ce que je dis, ton code réagit comme s'il devait être utilisé après que le service provider pour le format MP3 a été activé.










0
babylone78 Messages postés 8 Date d'inscription mardi 13 avril 2004 Statut Membre Dernière intervention 11 janvier 2011
22 déc. 2010 à 10:51
Pourtant le code pour encoder un fichier wav en mp3 marche correctement.
Mp3Encoder.writeFile("myAudio.wav");

C'est peut etre parce qu'il faut decoder les mp3 en PCM et reencoder pour concatener ?
Ca serait compliqué et trop couteux en temps... est ce que tu sais si ca serait plus facile en ogg ?
C'est quand même dingue qu'on puisse pas encoder de l'audio en format compressé à la volée

/*
 *	Mp3Encoder.java
 */


package voicestream.audiolan.recorder;
import	java.io.File;
import	java.io.IOException;

import	javax.sound.sampled.AudioFileFormat;
import	javax.sound.sampled.AudioFormat;
import	javax.sound.sampled.AudioInputStream;
import	javax.sound.sampled.AudioSystem;

/*
 *	Currently, there is no convenient method in Java Sound to specify non-standard Encodings.
 */
import	org.tritonus.share.sampled.AudioFileTypes;
import	org.tritonus.share.sampled.Encodings;


public class Mp3Encoder {
private static boolean DEBUG = false;
private static boolean dumpExceptions=false;
private static boolean traceConverters=false;
private static boolean quiet=false;

// currently, there is no convenient method in Java Sound to specify non-standard Encodings.
// using tritonus' proposal to overcome this.
private static final AudioFormat.Encoding	MPEG1L3 = Encodings.getEncoding("MPEG1L3");
private static final AudioFileFormat.Type	MP3 = AudioFileTypes.getType("MP3", "mp3");



private static AudioInputStream getInStream(String filename)
throws IOException {
File	file = new File(filename);
AudioInputStream	ais = null;
try {
ais = AudioSystem.getAudioInputStream(file);
} catch (Exception e) {
if (dumpExceptions) {
e.printStackTrace();
} else if (!quiet) {
System.out.println("Error: " + e.getMessage());
}
}
if (ais == null) {
throw new IOException("Cannot open "" + filename + """);
}
return ais;
}



public static String stripExtension(String filename) {
int	ind = filename.lastIndexOf(".");
if (ind == -1
        || ind == filename.length()
        || filename.lastIndexOf(File.separator) > ind) {
// when dot is at last position,
// or a slash is after the dot, there isn't an extension
return filename;
}
return filename.substring(0, ind);
}



/* first version. Remains here for documentation how to
 * get a stream with complete description of the target format.
 */
public static AudioInputStream getConvertedStream2(
    	AudioInputStream sourceStream,
    	AudioFormat.Encoding targetEncoding)
throws Exception {
AudioFormat sourceFormat = sourceStream.getFormat();
if (!quiet) {
System.out.println("Input format: " + sourceFormat);
}
// build the output format
AudioFormat targetFormat = new AudioFormat(
                               targetEncoding,
                               sourceFormat.getSampleRate(),
                               AudioSystem.NOT_SPECIFIED,
                               sourceFormat.getChannels(),
                               AudioSystem.NOT_SPECIFIED,
                               AudioSystem.NOT_SPECIFIED,
                               false); // endianness doesn't matter
// construct a converted stream
AudioInputStream targetStream = null;
if (!AudioSystem.isConversionSupported(targetFormat, sourceFormat)) {
if (DEBUG && !quiet) {
System.out.println("Direct conversion not possible.");
System.out.println("Trying with intermediate PCM format.");
}
AudioFormat intermediateFormat = new AudioFormat(
                                     AudioFormat.Encoding.PCM_SIGNED,
                                     sourceFormat.getSampleRate(),
                                     16,
                                     sourceFormat.getChannels(),
                                     2 * sourceFormat.getChannels(), // frameSize
                                     sourceFormat.getSampleRate(),
                                     false);
if (AudioSystem.isConversionSupported(intermediateFormat, sourceFormat)) {
// intermediate conversion is supported
sourceStream = AudioSystem.getAudioInputStream(intermediateFormat, sourceStream);
}
}
targetStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);
if (targetStream == null) {
throw new Exception("conversion not supported");
}
if (!quiet) {
if (DEBUG) {
System.out.println("Got converted AudioInputStream: " + targetStream.getClass().getName());
}
System.out.println("Output format: " + targetStream.getFormat());
}
return targetStream;
}



public static AudioInputStream getConvertedStream(
    	AudioInputStream sourceStream,
    	AudioFormat.Encoding targetEncoding)
throws Exception {
AudioFormat sourceFormat = sourceStream.getFormat();
if (!quiet) {
System.out.println("Input format: " + sourceFormat);
}

// construct a converted stream
AudioInputStream targetStream = null;
if (!AudioSystem.isConversionSupported(targetEncoding, sourceFormat)) {
if (DEBUG && !quiet) {
System.out.println("Direct conversion not possible.");
System.out.println("Trying with intermediate PCM format.");
}
AudioFormat intermediateFormat = new AudioFormat(
                                     AudioFormat.Encoding.PCM_SIGNED,
                                     sourceFormat.getSampleRate(),
                                     16,
                                     sourceFormat.getChannels(),
                                     2 * sourceFormat.getChannels(), // frameSize
                                     sourceFormat.getSampleRate(),
                                     false);
if (AudioSystem.isConversionSupported(intermediateFormat, sourceFormat)) {
// intermediate conversion is supported
sourceStream = AudioSystem.getAudioInputStream(intermediateFormat, sourceStream);
}
}
targetStream = AudioSystem.getAudioInputStream(targetEncoding, sourceStream);
if (targetStream == null) {
throw new Exception("conversion not supported");
}
if (!quiet) {
if (DEBUG) {
System.out.println("Got converted AudioInputStream: " + targetStream.getClass().getName());
}
System.out.println("Output format: " + targetStream.getFormat());
}
return targetStream;
}



public static int writeFile(String inFilename) {
int writtenBytes = -1;
try {
AudioFileFormat.Type targetType = MP3;
AudioInputStream ais = getInStream(inFilename);
ais = getConvertedStream(ais, MPEG1L3);

// construct the target filename
String outFilename = stripExtension(inFilename) + "." + targetType.getExtension();

// write the file
if (!quiet) {
System.out.println("Writing " + outFilename + "...");
}
writtenBytes = AudioSystem.write(ais, targetType, new File(outFilename));
ais.close();
if (DEBUG && !quiet) {
System.out.println("Effective parameters of output file:");
try {
String version=System.getProperty("tritonus.lame.encoder.version", "");
if (version!="") {
System.out.println("  Version      = "+version);
}
System.out.println("  Quality      = "+System.getProperty
                   ("tritonus.lame.effective.quality", "<none>"));
System.out.println("  Bitrate      = "+System.getProperty
                   ("tritonus.lame.effective.bitrate", "<none>"));
System.out.println("  Channel Mode = "+System.getProperty
                   ("tritonus.lame.effective.chmode", "<none>"));
System.out.println("  VBR mode     = "+System.getProperty
                   ("tritonus.lame.effective.vbr", "<none>"));
System.out.println("  Sample rate  = "+System.getProperty
                   ("tritonus.lame.effective.samplerate", "<none>"));
System.out.println("  Encoding     = "+System.getProperty
                   ("tritonus.lame.effective.encoding", "<none>"));
} catch (Throwable t1) {}
}
} catch (Throwable t) {
if (dumpExceptions) {
t.printStackTrace();
} else if (!quiet) {
System.out.println("Error: " + t.getMessage());
}
}
return writtenBytes;
}



// returns the first index in args where the files start
public static int parseArgs(String[] args) {
if (args.length == 0) {
usage();
}
// parse options
try {
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("--help")) {
usage();
}
if (arg.length() > 3 || arg.length() < 2 || !arg.startsWith("-")) {
return i;
}
char cArg = arg.charAt(1);
// options without parameter
if (cArg == 'v') {
DEBUG=true;
continue;
} else if (cArg == 'e') {
dumpExceptions=true;
continue;
} else if (cArg == 't') {
org.tritonus.share.TDebug.TraceAudioConverter=true;
continue;
} else if (cArg == 's') {
quiet=true;
continue;
} else if (cArg == 'V') {
try {
System.setProperty("tritonus.lame.vbr", "true");
} catch (Throwable t1) {}
continue;
} else if (cArg == 'h') {
usage();
}
// options with parameter
if (args.length < i + 2) {
throw new Exception("Missing parameter or unrecognized option "+arg+".");
}
String param = args[i + 1];
i++;
switch (cArg) {
case 'q':
try {
System.setProperty("tritonus.lame.quality", param);
} catch (Throwable t2) {}
break;
case 'b':
try {
System.setProperty("tritonus.lame.bitrate", param);
} catch (Throwable t3) {}
break;
default:
throw new Exception("Unrecognized option "+arg+".");
}
}
throw new Exception("No input file(s) are given.");
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
return 0; // statement not reached
}



public static void main(String[] args) {
//try {
//	System.out.println("Librarypath=" + System.getProperty("java.library.path", ""));
//} catch (Throwable t) {}

int firstFileIndex = parseArgs(args);
int inputFiles = 0;
int success = 0;
long totalTime = System.currentTimeMillis();
for (int i = firstFileIndex; i < args.length; i++) {
long time = System.currentTimeMillis();
int bytes = writeFile(args[i]);
time = System.currentTimeMillis()-time;
inputFiles++;
if (bytes >= 0) {
if (bytes > 0) {
success++;
}
if (!quiet) {
System.out.println("Wrote " + bytes + " bytes in "
                   + (time / 60000) + "m " + ((time/1000) % 60) + "s "
                   + (time % 1000) + "ms ("
                   + (time/1000) + "s).");
}
}
}
totalTime = System.currentTimeMillis() - totalTime;
if ((DEBUG && quiet) || !quiet) {
// this IS displayed in silent DEBUG mode
System.out.println("From " + inputFiles + " input file" + (inputFiles == 1 ? "" : "s") + ", "
                   + success + " file" + (success == 1 ? " was" : "s were") + " converted successfully in "
                   + (totalTime / 60000) + "m " + ((totalTime/1000) % 60) + "s  ("
                   + (totalTime/1000) + "s).");
}
System.exit(0);
}



/**	Display a message of how to call this program.
 */
public static void usage() {
System.out.println("Mp3Encoder - convert audio files to mp3 (layer III of MPEG 1, MPEG 2 or MPEG 2.5");
System.out.println("java Mp3Encoder <options> <source file> [<source file>...]");
System.out.println("The output file(s) will be named like the source file(s) but");
System.out.println("with mp3 file extension.");
System.out.println("");
System.out.println("You need LAME 3.88 or later. Get it from http://sourceforge.net/projects/lame/");
System.out.println("");
System.out.println("<options> may be a combination of the following:");
System.out.println("-q <quality>  Quality of output mp3 file. In VBR mode, this affects");
System.out.println("              the size of the mp3 file. (Default middle)");
System.out.println("              One of: lowest, low, middle, high, highest");
System.out.println("-b   Bitrate in KBit/s. Useless in VBR mode. (Default 128)");
System.out.println("              One of: 32 40 48 56 64 80 96 112 128 160 192 224 256 320 (MPEG1)");
System.out.println("              Or: 8 16 24 32 40 48 56 64 80 96 112 128 144 160 (MPEG2 and MPEG2.5");
System.out.println("-V            VBR (variable bit rate) mode. Slower, but potentially better");
System.out.println("              quality. (Default off)");
System.out.println("-v            Be verbose.");
System.out.println("-s            Be silent.");
System.out.println("-e            Debugging: Dump stack trace of exceptions.");
System.out.println("-t            Debugging: trace execution of converters.");
System.out.println("-h | --help   Show this message.");
System.exit(1);
}

}



/*** Mp3Encoder.java ***/



0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Utilisateur anonyme
22 déc. 2010 à 12:36
Ca veut simplement dire que ton encodeur marche mais pas ton décodeur.
















0
Rejoignez-nous