一、环境

JDK1.8 、IDEA

二、实践

准备:一个.wav后缀的音频文件
1)AudioClip rt.jar java.applet

package audio;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.URL;

public class AudioTest {
    public static void main(String[] args) throws Exception{
        URL url = new File("1.wav").toURI().toURL();
        AudioClip audioClip = new Applet().newAudioClip(url);
        audioClip.play();
        Thread.sleep(5000);
        audioClip.stop();
    }
}

play/stop/loop自由组合,播放5秒钟停止,stop后再play还是从头开始播放。audioClip.loop()也是从头开始(实验结果)。
2)AudioStream rt.jar sun.audio

package audio;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class AudioTest02 {
    public static void main(String[] args) throws IOException, InterruptedException {
        InputStream in = new FileInputStream("1.wav");
        AudioStream as = new AudioStream(in);

        AudioPlayer.player.start(as);
        Thread.sleep(20000);
        AudioPlayer.player.stop(as);
    }
}

这个stop之后再start可以继续之前的地方播放。

上边两种都不支持mp3,支持AIFF /AU /WAV /MIDI (type 0 and type 1 files) /RMF
3)JLayer- MP3 library

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class AudioTest03 {
    public static void main(String[] args) {
        try {
            Player player = new Player(new FileInputStream("a.mp3"));
            player.play();
        }  catch (JavaLayerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

这个是支持MP3,但是一旦播放就停不了,这是因为占用主线程阻塞播放,可以单独再启用一个线程播放

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class AudioTest03 {
    public static void main(String[] args) {
        try {
            Player player = new Player(new FileInputStream("a.mp3"));


            new Thread(()->{
                //调用播放方法进行播放
                try {
                    player.play();
                } catch (JavaLayerException e) {
                    e.printStackTrace();
                }
            }).start();

            Thread.sleep(1000);
            player.close();
            
        }  catch (JavaLayerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
三、小记

慢慢探索、深入,争取写出点有意义的东西。简单播放停止可以了,怎么做一个和播放器一样的,可以随停随播的那种,继续深入吧。