简体   繁体   English

如何导航到 src 中的 wav.file(用于在 java 中播放声音)

[英]How is it possible to navigate to wav.file in src (for playing sound in java)

I've looked at different solutions at Stackoverflow to play a sound in Java.我在 Stackoverflow 上查看了不同的解决方案,以在 Java 中播放声音。 The example given below (from another topic) is the one I would like to use.下面给出的示例(来自另一个主题)是我想使用的示例。

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();
   }
}

But how is it possible to get the file from src folder (it's already in my src)?但是如何从 src 文件夹中获取文件(它已经在我的 src 中)? Or is there another code solution to play a.wav file from src/... folder?或者是否有另一种代码解决方案可以从 src/... 文件夹播放 a.wav 文件?

Thanks in advance!提前致谢!

This code这段代码

this.getClass().getClassLoader().getResource(...) 

will fetch a resource relative to where classes are lodaed from.将获取与加载的位置相关的资源。 The runtime doesn't know anything about sources .运行时对sources一无所知。 If you move your file to compiled classes folder, this should work.如果您将文件移动到已编译的类文件夹,这应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM