Using music in a java program

六月ゝ 毕业季﹏ 提交于 2019-12-08 13:02:43

问题


I was trying out the method of creating a background music for a java program, but it displayed an IO excedption error when i clicked the play button.

package javaentertainment;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.*;
import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class Music
{

    public static void main(String args[])
    {
        JFrame frame=new JFrame();
        frame.setSize(100,100);
        JButton button=new JButton("P L A Y");
        frame.add(button);
        button.addActionListener(new AL());
        frame.show();
    }

   public static class AL implements ActionListener
   {

        public void actionPerformed(ActionEvent e) {
            music();
        }
    }

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

        try
        {
            BGM = new AudioStream(new FileInputStream("Vision.wmv"));
            MD=BGM.getData();
            loop=new ContinousAudioDataStream(MD);

        }
        catch (IOException ex)
        {
           System.out.println(ex);
        }

        MGP.start(loop); // word loop was underlined by netbeans
    }
}

When I run the program and click on play it displays the following error, java.io.IOException: could not create audio stream from input stream


回答1:


You should use JMF (Java Media Framework). For your interest: The list of accepted formats can be found here.

In short, it supports AIFF, AVI, GSM, MVR, MID, MPG, MP2, MOV, AU and WAV files.

But there is a workarond as stated here:

On a side note, if you add a mime-setting in JMFRegistry to map Windows Media content (such as .asf and .wmv) to the content-type "video/mpeg", JMF can actually play Windows Media or any other DirectShow file (and only file - http wont work).




回答2:


I would be surprised if Java can hand Windows Media format samples - try converting the .wmv to a .wav file and see if it works then.




回答3:


Just got this, as well.

java.io.IOException: could not create AudioData object 

Appears from the source [1] that this means that "your audio file is size > 1 MB" and it doesn't like that for whatever reason. Maybe a bug [?] that they don't accomodate for this.

One work-around might be to use JMF instead, as suggested, if you want looping to work for large files anyway.

[1] http://www.docjar.com/docs/api/sun/audio/AudioStream.html#getData



来源:https://stackoverflow.com/questions/3274775/using-music-in-a-java-program

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