如何读取音频文件?我应该使用哪种方法?

3
我有一个带有2个按钮的面板。当我点击按钮1时,我想要简单地读取一个音频文件(在这种情况下是.WAV格式)。然后,当我点击按钮2时,我想停止播放音乐。
我做了一些研究,但是对于不同的方法感到有些困惑。在我的情况下,哪种方法最好?有人能解释一下AudioClip、JavaSound和JavaMediaFramework之间的区别吗?
我也尝试了一个例子,但其中包含错误。
这是我的Main.class:
import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class Main
{
    public static void main(String[] args) 
    {
           SoundPlayer player = new SoundPlayer("C:/Documents and Settings/All Users/Documents/Ma musique/Échantillons de musique/Symphonie n° 9 de Beethoven (scherzo).wma");
           InputStream stream = new ByteArrayInputStream(player.getSamples()); 
           player.play(stream);
    }
}

这是我的 SoundPlayer.class 文件:
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.*;

public class SoundPlayer 
{
    private AudioFormat format;
    private byte[] samples;
    /**
     * 
     * @param filename le lien vers le fichier song (URL ou absolute path)
     */
    public SoundPlayer(String filename)
    {
        try
        {
            AudioInputStream stream = AudioSystem.getAudioInputStream(new File(filename));
            format = stream.getFormat();
            samples = getSamples(stream);
        }
        catch (UnsupportedAudioFileException e){e.printStackTrace();}
        catch (IOException e){e.printStackTrace();}
    }

    public byte[] getSamples()
    {
        return samples;
    }

    public byte[] getSamples(AudioInputStream stream)
    {
        int length = (int)(stream.getFrameLength() * format.getFrameSize());
        byte[] samples = new byte[length];
        DataInputStream in = new DataInputStream(stream);
        try
        {
            in.readFully(samples);
        }
        catch (IOException e){e.printStackTrace();}
        return samples;
    }

    public void play(InputStream source)
    {
        int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10);
        byte[] buffer = new byte[bufferSize];
        SourceDataLine line;
        try
        {
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            line = (SourceDataLine)AudioSystem.getLine(info);
            line.open(format, bufferSize);
        }
        catch (LineUnavailableException e)
        {
            e.printStackTrace();
            return;
        }
        line.start();

        try
        {
            int numBytesRead = 0;
            while (numBytesRead != -1)
            {
                numBytesRead = source.read(buffer, 0, buffer.length);
                if (numBytesRead != -1)
                    line.write(buffer, 0, numBytesRead);
            }
        }
        catch (IOException e){e.printStackTrace();}

        line.drain();
        line.close();
    }
}

LOGCAT :

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
    at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
    at SoundPlayer.<init>(SoundPlayer.java:19)
    at Main.main(Main.java:8)
Exception in thread "main" java.lang.NullPointerException
    at java.io.ByteArrayInputStream.<init>(Unknown Source)
    at Main.main(Main.java:9)

In advance, thanks a lot !

4个回答

1

那个异常将会保留。*.wma文件不被标准支持。

最简单的解决方案是使用*.wav文件或其他受支持的文件。

您可以在以下网址获取更多信息:

https://stackoverflow.com/tags/javasound/info


1
SoundPlayer player = new SoundPlayer("C:/Documents and Settings/All Users/" + 
  "Documents/Ma musique/Échantillons de musique/" + 
   "Symphonie n° 9 de Beethoven (scherzo).wma")

啊,WMA。很好的格式,但Java(标准版)没有提供支持它的服务提供程序接口。您需要提供SPI来允许Java Sound支持它,或者使用不同的API。我不知道有哪些API可以支持WMA。您能用其他格式进行编码吗?请参阅Java Sound信息页面以了解支持MP3的方法,但需要JMF的MP3 SPI。

0

我已经找到了解决我的问题的方法。 在我的情况下,使用JAVAZOOM库是很好的选择。

这里有一个示例,只在启动时播放音频文件(没有图形部分)

public class Sound 
{   
    private boolean isPlaying = false;
    private AdvancedPlayer player = null;

    public Sound(String path) throws Exception 
    {
        InputStream in = (InputStream)new BufferedInputStream(new FileInputStream(new File(path)));
        player = new AdvancedPlayer(in);
    }

    public Sound(String path,PlaybackListener listener) throws Exception 
    {
        InputStream in = (InputStream)new BufferedInputStream(new FileInputStream(new File(path)));
        player = new AdvancedPlayer(in);
        player.setPlayBackListener(listener);
    }

    public void play() throws Exception
    {
        if (player != null) 
        {
            isPlaying = true;
            player.play();
        }
    }

    public void play(int begin,int end) throws Exception 
    {
        if (player != null) 
        {
            isPlaying = true;
            player.play(begin,end);
        }
    }

    public void stop() throws Exception 
    {
        if (player != null)
        {
            player.stop();
            isPlaying = false;

        }
    }

    public boolean isPlaying() 
    {
        return isPlaying;
    }

    public static void main(String[] args) 
    {
        System.out.println("lecture de son");
        try 
        {
            Sound sound = new Sound("C:/Documents and Settings/cngo/Bureau/Stage-Save/TCPIP_AndroidJava/TCPIP_V6_Sound/OpeningSuite.mp3");
            System.out.println("playing : " + sound.isPlaying());
            sound.play();
            System.out.println("playing : " + sound.isPlaying());
        } 
        catch (Exception e){e.printStackTrace();}
    }
}

感谢@murtaza.webdev提供的答案!

0

请写下您的音乐文件的完整路径,它将正常工作。


当我写完整路径时,出现了另一个错误。你有什么想法吗? - Tofuw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接