gpt4 book ai didi

java - 在 Java 中启动和停止声音

转载 作者:行者123 更新时间:2023-12-02 22:24:29 24 4
gpt4 key购买 nike

类似于 this question ,我想在 Java 应用程序中播放 WAV 文件 - 但是,我还希望能够暂停、恢复和重新启动声音。我猜我可以通过暂停然后创建一个新声音来重新启动,但是我首先如何暂停和恢复?

请注意,我的声音约为 15 分钟和 152.8mb。如果有办法用 MP3 文件(相同长度,20.8mb)来做到这一点,那就更好了。

最佳答案

要播放 WAV 文件,请参阅此问题的答案:
Problem with Javas Audio Clips on frequent playback of beep sounds

要播放 MP3,您可以使用 JLayer这是一个相当小的 jar(我认为 100k,可能更小),您可以将其与您的应用程序捆绑在一起。

这是一个相当不错的示例,说明如何使用它:
MP3.java (来自 How to play an MP3 file in Java)

/*************************************************************************
* Compilation: javac -classpath .:jl1.0.jar MP3.java (OS X)
* javac -classpath .;jl1.0.jar MP3.java (Windows)
* Execution: java -classpath .:jl1.0.jar MP3 filename.mp3 (OS X / Linux)
* java -classpath .;jl1.0.jar MP3 filename.mp3 (Windows)
*
* Plays an MP3 file using the JLayer MP3 library.
*
* Reference: http://www.javazoom.net/javalayer/sources.html
*
*
* To execute, get the file jl1.0.jar from the website above or from
*
* http://www.cs.princeton.edu/introcs/24inout/jl1.0.jar
*
* and put it in your working directory with this file MP3.java.
*
*************************************************************************/

import java.io.BufferedInputStream;
import java.io.FileInputStream;

import javazoom.jl.player.Player;

public class MP3 {
private String filename;
private Player player;

// constructor that takes the name of an MP3 file
public MP3(String filename) {
this.filename = filename;
}

public void close() { if (player != null) player.close(); }

// play the MP3 file to the sound card
public void play() {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}

// run in new thread to play in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();

}


// test client
public static void main(String[] args) {
String filename = args[0];
MP3 mp3 = new MP3(filename);
mp3.play();

// do whatever computation you like, while music plays
int N = 4000;
double sum = 0.0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
sum += Math.sin(i + j);
}
}
System.out.println(sum);

// when the computation is done, stop playing it
mp3.close();

// play from the beginning
mp3 = new MP3(filename);
mp3.play();

}

}

关于java - 在 Java 中启动和停止声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6701262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com