gpt4 book ai didi

java - 如何使用源码包中的文件(路径是什么?)

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

好吧,标题可能不完全正确,但这就是我的意思:我有一个类,其方法如下所示:

package chess;

import java.io.*;
import sun.audio.*;

public class SoundPlayer

{
public static void Play(String AudioFile)

throws Exception

{
// open the sound file as a Java input stream
InputStream in = new FileInputStream(AudioFile);

// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);

// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);
}
}

我想要做的是在.jar中编译一个.wav文件以及所有.java文件,并能够用这种方法播放它。要批量执行此操作,我所要做的就是输入文件名,它使用当前目录。我在这里尝试过,但没有成功。所以,我的最后一个问题是:

我需要在“/sound.wav”之前输入什么才能让我的程序从源目录引用它?抱歉,如果我没有说清楚。我到处搜索过,但我想我不知道到底要在谷歌上搜索什么,因为我没有找到任何解释。

最佳答案

您可以使用 ClassLoader.getResourceAsStream() 来实现

示例:

 // open the sound file as a Java input stream
InputStream in = SoundPlayer.class.getClassLoader().getResourceAsStream("yoursound.wav");

// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);

// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);

关于java - 如何使用源码包中的文件(路径是什么?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435143/

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