gpt4 book ai didi

java - 从 Java 播放歌曲

转载 作者:行者123 更新时间:2023-11-29 07:43:19 25 4
gpt4 key购买 nike

我正在尝试播放 Java 中的歌曲。我尝试了很多不同的方法,但它们都失败了,给我这样的错误:

Exception in thread "main" java.io.FileNotFoundException: \workspace\playsound\song.wav (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at com.sun.media.sound.WaveFloatFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at playsound.LoopSound.main(LoopSound.java:20)

我所需要的只是一种从我的桌面/src 中获取 song.wav 并使其播放的简单方法。这适用于注释掉的链接,但不适用于文件:

package playsound;
import java.net.URL;

import javax.sound.sampled.*;

import java.io.File;

public class LoopSound {

public static void main(String[] args) throws Exception {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
File file = new File("c:/Users/liam/workspace/playsound/song.wav");
System.out.println("length : " + file.length());
URL url = new URL("file:///workspace\\playsound\\song.wav");
//"http://www.intriguing.com/mp/_sounds/hg/fart.wav");

Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(5);
javax.swing.JOptionPane.showMessageDialog(null, "Close to exit!");
}
}

我确定它在那里,因为我已经测试过它在哪里:

Working Directory = C:\Users\liam\workspace\playsound

它可以告诉我它有多大:

length : 2914585

public static void main(String[] args) throws Exception {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
File file = new File("c:/Users/liam/workspace/playsound/song.wav");
System.out.println("length : " + file.length());
new File("workspace\\playsound\\song.wav").toURI().toURL();

这给了我错误:

Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at playsound.musicplayer.main(musicplayer.java:20)

最佳答案

如果你可以播放一个网址,那么我建议你尝试以下方法:

new File(path).toURI().toURL();

让我知道它是否有效。

同样根据javadocs ,你可以直接使用一个文件。所以你不需要 URL。如果您收到 FileNotFoundException,那是因为路径错误、文件不存在或您没有正确的权限。

关于java - 从 Java 播放歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28015651/

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