我怎样才能用 Java 播放声音?

我希望能够在我的程序中播放声音文件。我应该在哪里查看?

381861 次浏览

一个糟糕的例子:

import  sun.audio.*;    //import the sun.audio package
import  java.io.*;


//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);


// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);


// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);


// Similarly, to stop the audio.
AudioPlayer.player.stop(as);

我写了下面的代码,工作得很好。但我认为它只适用于 .wav格式。

public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}

除了导入在小应用程序和应用程序中都可以使用的声音文件之外,还有一种替代方法: 将音频文件转换为。Java 文件,并简单地在代码中使用它们。

我已经开发了一个工具,使这个过程容易得多。它大大简化了 JavaSound API。

Http://stephengware.com/projects/soundtoclass/

不久前,我创建了一个游戏框架,用于 Android 和桌面,桌面部分处理声音,也许可以作为你需要的灵感。

Https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/sound.java

这里是参考代码。

package com.athanazio.jaga.desktop.sound;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;


import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;


public class Sound {


AudioInputStream in;


AudioFormat decodedFormat;


AudioInputStream din;


AudioFormat baseFormat;


SourceDataLine line;


private boolean loop;


private BufferedInputStream stream;


// private ByteArrayInputStream stream;


/**
* recreate the stream
*
*/
public void reset() {
try {
stream.reset();
in = AudioSystem.getAudioInputStream(stream);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);


} catch (Exception e) {
e.printStackTrace();
}
}


public void close() {
try {
line.close();
din.close();
in.close();
} catch (IOException e) {
}
}


Sound(String filename, boolean loop) {
this(filename);
this.loop = loop;
}


Sound(String filename) {
this.loop = false;
try {
InputStream raw = Object.class.getResourceAsStream(filename);
stream = new BufferedInputStream(raw);


// ByteArrayOutputStream out = new ByteArrayOutputStream();
// byte[] buffer = new byte[1024];
// int read = raw.read(buffer);
// while( read > 0 ) {
// out.write(buffer, 0, read);
// read = raw.read(buffer);
// }
// stream = new ByteArrayInputStream(out.toByteArray());


in = AudioSystem.getAudioInputStream(stream);
din = null;


if (in != null) {
baseFormat = in.getFormat();


decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, baseFormat
.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat
.getSampleRate(), false);


din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);
}
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}


private SourceDataLine getLine(AudioFormat audioFormat)
throws LineUnavailableException {
SourceDataLine res = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}


public void play() {


try {
boolean firstTime = true;
while (firstTime || loop) {


firstTime = false;
byte[] data = new byte[4096];


if (line != null) {


line.start();
int nBytesRead = 0;


while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1)
line.write(data, 0, nBytesRead);
}


line.drain();
line.stop();
line.close();


reset();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}


}

要在 Java 中播放声音,可以参考以下代码。

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;


// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {


public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);


try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource("gameover.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}


public static void main(String[] args) {
new SoundClipTest();
}
}

我不想有这么多的代码行只是为了播放一个简单的该死的声音。如果您有 JavaFX 包(已经包含在我的 jdk 8中) ,那么可以使用这种方法。

private static void playSound(String sound){
// cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
URL file = cl.getResource(sound);
final Media media = new Media(file.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}

注意: 您需要 初始化 JavaFX。一个快速的方法是在应用程序中调用一次 JFXPanel ()的构造函数:

static{
JFXPanel fxPanel = new JFXPanel();
}

不管出于什么原因,wchargin 给出的最高答案是在调用 this.getClass () . getResourceAsStream ()时给我一个空指针错误。

对我起作用的是以下几点:

void playSound(String soundFile) {
File f = new File("./" + soundFile);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
}

我会用下面的声音播放:

 playSound("sounds/effects/sheep1.wav");

Sound/effect/sheep1.wav 位于 Eclipse 中我的项目的基本目录中(所以不在 src 文件夹中)。

这个线程相当老,但我已经确定了一个可能有用的选项。

与使用 JavaAudioStream库不同,您可以使用外部程序,如 WindowsMediaPlayer 或 VLC,并通过 Java 使用控制台命令运行它。

String command = "\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\" \"C:/song.mp3\"";
try {
Process p = Runtime.getRuntime().exec(command);
catch (IOException e) {
e.printStackTrace();
}

这也将创建一个单独的进程,可以控制它的程序。

p.destroy();

当然,这比使用内部库要花费更长的时间来执行,但是可能有一些程序可以更快地启动,而且可能不需要给定某些控制台命令的 GUI。

如果时间不是关键,那么这是有用的。

我很惊讶没人建议使用 Applet。使用 Applet.您必须提供作为 wav文件的哔哔声音频文件,但它可以工作。我在 Ubuntu 上试过这个:

package javaapplication2;


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


public class JavaApplication2 {


public static void main(String[] args) throws MalformedURLException {
File file = new File("/path/to/your/sounds/beep3.wav");
URL url = null;
if (file.canRead()) {url = file.toURI().toURL();}
System.out.println(url);
AudioClip clip = Applet.newAudioClip(url);
clip.play();
System.out.println("should've played by now");
}
}
//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav

对我有用,简单的变体

public void makeSound(){
File lol = new File("somesound.wav");
    



try{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(lol));
clip.start();
} catch (Exception e){
e.printStackTrace();
}
}

我面临许多问题,以发挥 mp3文件格式 因此,使用一些 < a href = “ https://online-Audio-Converter.com/”rel = “ nofollow norefrer”> 在线转换器将其转换为. wav

然后在代码之下使用(它比 mp3支持更容易)

try
{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(GuiUtils.class.getResource("/sounds/success.wav")));
clip.start();
}
catch (Exception e)
{
LogUtils.logError(e);
}
import java.net.URL;
import java.net.MalformedURLException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.io.File;
public class SoundClipTest{
//plays the sound
public static void playSound(final String path){
try{
final File audioFile=new File(path);
AudioInputStream audioIn=AudioSystem.getAudioInputStream(audioFile);
Clip clip=AudioSystem.getClip();
clip.open(audioIn);
clip.start();
long duration=getDurationInSec(audioIn);
//System.out.println(duration);
//We need to delay it otherwise function will return
//duration is in seconds we are converting it to milliseconds
Thread.sleep(duration*1000);
}catch(LineUnavailableException | UnsupportedAudioFileException | MalformedURLException | InterruptedException exception){
exception.printStackTrace();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
//Gives duration in seconds for audio files
public static long getDurationInSec(final AudioInputStream audioIn){
final AudioFormat format=audioIn.getFormat();
double frameRate=format.getFrameRate();
return (long)(audioIn.getFrameLength()/frameRate);
}
////////main//////
public static void main(String $[]){
//SoundClipTest test=new SoundClipTest();
SoundClipTest.playSound("/home/dev/Downloads/mixkit-sad-game-over-trombone-471.wav");
}
}