java mp3 wav_在Java中播放.mp3和.wav?

使用标准的javax.sound API,一个Maven依赖,完全开源(需要 Java 7 ):

pom.xml

com.googlecode.soundlibs

tritonus-share

0.3.7-2

com.googlecode.soundlibs

mp3spi

1.9.5-1

com.googlecode.soundlibs

vorbisspi

1.0.3-1

代码

import java.io.File;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;

import javax.sound.sampled.AudioInputStream;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.DataLine.Info;

import javax.sound.sampled.LineUnavailableException;

import javax.sound.sampled.SourceDataLine;

import javax.sound.sampled.UnsupportedAudioFileException;

import static javax.sound.sampled.AudioSystem.getAudioInputStream;

import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;

public class AudioFilePlayer {

public static void main(String[] args) {

final AudioFilePlayer player = new AudioFilePlayer ();

player.play("something.mp3");

player.play("something.ogg");

}

public void play(String filePath) {

final File file = new File(filePath);

try (final AudioInputStream in = getAudioInputStream(file)) {

final AudioFormat outFormat = getOutFormat(in.getFormat());

final Info info = new Info(SourceDataLine.class, outFormat);

try (final SourceDataLine line =

(SourceDataLine) AudioSystem.getLine(info)) {

if (line != null) {

line.open(outFormat);

line.start();

stream(getAudioInputStream(outFormat, in), line);

line.drain();

line.stop();

}

}

} catch (UnsupportedAudioFileException

| LineUnavailableException

| IOException e) {

throw new IllegalStateException(e);

}

}

private AudioFormat getOutFormat(AudioFormat inFormat) {

final int ch = inFormat.getChannels();

final float rate = inFormat.getSampleRate();

return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);

}

private void stream(AudioInputStream in, SourceDataLine line)

throws IOException {

final byte[] buffer = new byte[4096];

for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {

line.write(buffer, 0, n);

}

}

}

参考文献:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值