How to play an MP3 File using Java?

我的未来我决定 提交于 2019-12-11 01:26:31

问题


Using Applet.AudioClip I'm able to play .wav files, but if I try to do that on an MP3 file, then no audio seems to get played even though no exceptions are thrown.

Is there any way to play MP3s with Java, whether using Swing, Java FX, or any other Java technologies?


回答1:


package test;

import java.io.File;

import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;

public class AudioTest {
public static void main(String[] args) {
    Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
    Format input2 = new AudioFormat(AudioFormat.MPEG);
    Format output = new AudioFormat(AudioFormat.LINEAR);
    PlugInManager.addPlugIn(
        "com.sun.media.codec.audio.mp3.JavaDecoder",
        new Format[]{input1, input2},
        new Format[]{output},
        PlugInManager.CODEC
    );
    try{
        Player player = Manager.createPlayer(new MediaLocator(new File("data/audioFiles/abc.mp3").toURI().toURL()));
        player.start();
    }
    catch(Exception ex){
        ex.printStackTrace();
    }
}
}

Hope it helps..



来源:https://stackoverflow.com/questions/12293071/how-to-play-an-mp3-file-using-java

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