简体   繁体   English

播放jar文件中的音频

[英]Playing audio from jar file

I have found plenty of threads on this subject but i still dont get it to work. 我在这个问题上发现了很多话题,但是我仍然没有使它起作用。 It works easily from the compiler but not from the jar file. 它可以从编译器轻松运行,但不能从jar文件运行。 It seems the jar file finds the audio file but it just doest play it. 似乎jar文件找到了音频文件,但它没有播放。

import sun.audio.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

@SuppressWarnings({"serial","restriction"})
public class JarSoundTest1 extends JFrame { 
  JButton button;
  InputStream in;
  AudioStream as;

  public JarSoundTest1() throws Exception {

      JOptionPane.showMessageDialog(null, this.getClass().getResource("blopp.wav"));          

      button = new JButton("Click to Blopp!");
      button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try{
                in = this.getClass().getResourceAsStream("blopp.wav");
                as = new AudioStream (in);
                AudioPlayer.player.start(as);

                JOptionPane.showMessageDialog(null, "try");

            }catch(Exception ex){

                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "catch");               
            }
        }       
      });
      add(button);    
  }

  public static final void main(String[] args) throws Exception {
      JFrame frame = new JarSoundTest1();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(200, 200);
      frame.setVisible(true);     
  }  
}

The JOptionPane displays "try" every time the button is clicked, indicating the file is found i assume? 每次单击该按钮时,JOptionPane都会显示“尝试”,表明我认为找到了该文件? Still no sound is played. 仍然没有声音播放。 I have tried using audio files placed both inside and outside the jar file. 我尝试使用放置在jar文件内部和外部的音频文件。 Help to understand this is much appreciated. 帮助理解这一点非常感谢。

Ok, I got it finally. 好的,我终于明白了。 I don't think it is a sound issue I am quite sure as I can get a wav to play with code very similar to yours, it is a resource issue within jars which can be quite tricky. 我不认为这是一个声音问题,我可以肯定,因为我可以通过wav来处理与您的代码非常相似的代码,这是jar中的一个资源问题,可能非常棘手。 I would suggest the following based upon experiments in editing the above code: 根据编辑上述代码的实验,我建议以下内容:

getClass vs getClassLoader getClass vs getClassLoader

If you use getClass, the path must begin with the forward slash, /. 如果使用getClass,则路径必须以正斜杠/开头。 So, if your .wav is at the top level, ./blopp.wav is the way to go. 因此,如果您的.wav位于顶层,那么./blopp.wav是您的最佳选择。 So likely that is the only adjustment you will need if the .wav file is recognized by sun.audio.*. 如果.wav文件被sun.audio。*识别,那么这可能是您唯一需要的调整。

If you can find the resource in the jar, but cannot hear audio, maybe try a different .wav file. 如果您可以在jar中找到该资源,但听不到声音,则可以尝试使用其他.wav文件。 Some good wav files are here 一些好的wav文件在这里

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

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