我的目标是从Java播放mp3文件。对于我采用的每种方法,它总是以LineUnavailableException
失败。
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new URL("http://localhost:8080/agriserver/facebook/sound/test6.mp3"));
Clip clip = AudioSystem.getClip(info);
clip.open(inputStream);
clip.start();
修复它的尝试失败:
以下是例外:
Exception in thread "main" javax.sound.sampled.LineUnavailableException: line with format MPEG1L3 48000.0 Hz, unknown bits per sample, stereo, unknown frame size, 41.666668 frames/second, not supported. at com.sun.media.sound.DirectAudioDevice$DirectDL.implOpen(DirectAudioDevice.java:494) at com.sun.media.sound.DirectAudioDevice$DirectClip.implOpen(DirectAudioDevice.java:1280) at com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:107) at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1061) at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1151) at Demo.playMp3(Demo.java:83)
答案 0 :(得分:3)
显然,必须将mp3读入一个流。必须将该流读入第二个流以对其进行解码。以下代码有效:
// read the file
AudioInputStream rawInput = AudioSystem.getAudioInputStream(new ByteArrayInputStream(data));
// decode mp3
AudioFormat baseFormat = rawInput.getFormat();
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, // Encoding to use
baseFormat.getSampleRate(), // sample rate (same as base format)
16, // sample size in bits (thx to Javazoom)
baseFormat.getChannels(), // # of Channels
baseFormat.getChannels()*2, // Frame Size
baseFormat.getSampleRate(), // Frame Rate
false // Big Endian
);
AudioInputStream decodedInput = AudioSystem.getAudioInputStream(decodedFormat, rawInput);
答案 1 :(得分:2)
好的 - 让我们先排除你的MP3文件和你的代码。
我对此进行了测试,效果很好。
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 {
private String filename;
private Player player;
// constructor that takes the name of an MP3 file
public MP3(String filename) {
this.filename = filename;
}
public void close() { if (player != null) player.close(); }
// play the MP3 file to the sound card
public void play() {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
// test client
public static void main(String[] args) {
String filename = args[0];
MP3 mp3 = new MP3(filename);
mp3.play();
}
}