Adding Music/Sound to Java Programs

喜欢而已 提交于 2019-12-11 08:38:08

问题


I'm making some mini java games and I was wondering how I can add sound/music to my programs. I watched a video on youtube and followed the code provided, however I get the following error: java.io.IOException: could not create audio stream from input stream

I noticed that others have asked the same question with the same code but the answers were not helpful. Here is the code:

import sun.audio.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class Project1 
{
public static void main(String[] args)
{
    JFrame frame = new JFrame();
    frame.setSize(200,200);
    frame.setLocationRelativeTo(null);
    JButton button = new JButton("Click me");
    frame.add(button);
    button.addActionListener(new AL());
    frame.setVisible(true);
}
    public static class AL implements ActionListener{
        public final void actionPerformed(ActionEvent e){
            music();
    }
}

    public static void music() 
    {       
        AudioPlayer MGP = AudioPlayer.player;
        AudioStream BGM;
        AudioData MD;

        ContinuousAudioDataStream loop = null;

        try
        {
            InputStream test = new FileInputStream("C:\\Music1.wmv");
            BGM = new AudioStream(test);
            AudioPlayer.player.start(BGM);
            //MD = BGM.getData();
            //loop = new ContinuousAudioDataStream(MD);

        }
        catch(FileNotFoundException e){
            System.out.print(e.toString());
        }
        catch(IOException error)
        {
            System.out.print(error.toString());
        }
        MGP.start(loop);
    }


}

回答1:


InputStream test = new FileInputStream("C:\\Music1.wmv");

Java Sound has no support for WMV & I've not heard of a Service Provider Interface that will support it. You'll need to convert the sound to an older file type.




回答2:


Use AudioInputStream for Taking audio files as input, Refer this




回答3:


Try using:

InputStream test = new FileInputStream("C:\\Music1.au");

Or:

InputStream test = new FileInputStream("C:\\Music1.wav");

Just convert your file to one of these audio files.



来源:https://stackoverflow.com/questions/20811728/adding-music-sound-to-java-programs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!