如何使用Java来播放MP3文件? [英] How to play an MP3 File using Java?

查看:218
本文介绍了如何使用Java来播放MP3文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Applet.AudioClip 我能够播放.wav文件,但如果我尝试这样做,在一个MP3文件,然后无音讯似乎变得连演虽然没有引发异常。

有没有办法发挥与Java的MP3,无论是使用的Swing,Java的外汇,或任何其他Java技术?


解决方案

 封装测试;进口的java.io.File;进口javax.media.Format;
进口javax.media.Manager;
进口javax.media.MediaLocator;
进口javax.media.Player;
进口javax.media.PlugInManager;
进口javax.media.format.AudioFormat;公共类AudioTest {
公共静态无效的主要(字串[] args){
    格式输入1 =新的AudioFormat的(AudioFormat.MPEGLAYER3);
    格式输入2 =新AudioFormat的(AudioFormat.MPEG);
    格式输出=新的AudioFormat的(AudioFormat.LINEAR);
    PlugInManager.addPlugIn(
        com.sun.media。codec.audio.mp3.JavaDe codeR
        新格式[] {输入1,输入2},
        新格式[] {}输出,
        插件管理。codeC
    );
    尝试{
        Player播放器= Manager.createPlayer(新的MediaLocator(新文件(数据/语音文件/ abc.mp3)toURI()的toURL()));
        player.start();
    }
    赶上(例外前){
        ex.printStackTrace();
    }
}
}

希望它可以帮助..

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?

解决方案

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..

这篇关于如何使用Java来播放MP3文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆