2 qiankai4 qiankai4 于 2013.05.25 22:57 提问

我用java写了一个小游戏,想插入背景音乐但不太会,求指教
package text;
import java.io.*;
import javax.sound.sampled.*;

public class text {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //创建一个实例

        AePlayWave apw = new AePlayWave("G:\\照片\\Sleep Away.mp3");
        apw.start();
    }

}
class AePlayWave extends Thread{
    private String filename;
    public AePlayWave(String wavfile){
        filename = wavfile;
    }
    public void run(){
        File soundFile = new File(filename);
        System.out.println(soundFile);
        AudioInputStream audioInputStream = null;
        try{
            audioInputStream =AudioSystem.getAudioInputStream(soundFile);   
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        return;
    }
    AudioFormat format = audioInputStream.getFormat();
    SourceDataLine auline = null;
    DataLine.Info info = new DataLine.Info(null, null);
    try{
        auline = (SourceDataLine) AudioSystem.getLine(info);
        auline.open(format);
    } catch(Exception e){
        e.printStackTrace();
        return ;
    }
    auline.start();
    int nBytesRead = 0;
    //这是缓冲

    byte[] abData = new byte[1024];
    try{
        while(nBytesRead != -1){
            nBytesRead = audioInputStream.read(abData, nBytesRead, nBytesRead);
                    if(nBytesRead >= 0){
                        auline.write(abData, 0, nBytesRead);
                    }
        }
        }catch (IOException e){
            e.printStackTrace();
            return ;
        }finally{
            auline.drain();
            auline.close();
        }
    }
}

这是我写的一部分代码,但是总是报错,报这样的错误:

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1187)
    at text.AePlayWave.run(text.java:26)

2个回答

franzhong
franzhong   2013.05.26 12:41
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
//if the File does not point to valid audio file data recognized by the system 

不支持mp3格式
换为wav试一下

yjsxxgm
yjsxxgm   2013.07.09 15:07

试一下.wav,应该可以放的。
参考地址:http://wenku.baidu.com/view/f7a2e083bceb19e8b8f6ba7f.html

Csdn user default icon
上传中...
上传图片
插入图片