gpt4 book ai didi

java - 如何在程序中添加背景音乐?

转载 作者:行者123 更新时间:2023-12-03 02:35:34 25 4
gpt4 key购买 nike

我试图将背景音乐添加到程序中,但是当我指定音频文件的路径时,会收到错误消息。我还能如何指定它(将发送给其他人)。因此该路径不能在我的系统上,它也必须位于JAR中。

package main;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

javax.sound.sampled.AudioSystem;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class Main extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
PlaySound();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public static void PlaySound() {
InputStream in;
try {
in = new FileInputStream(new File("/audio/Happy_Happy_Birthday.wav"));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);

}

}

public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 717, 508);
contentPane = new JPanel() {
/**
*
*/
private static final long serialVersionUID = 1L;

public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(
Main.class.getResource("/images/happy_birthday.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}

最佳答案

  • 使用URL而不是File加载剪辑。在部署时,这些资源可能会变成。在这种情况下,必须通过URL而不是File访问资源。有关标签的信息,请参见info page,以了解形成URL的方法。
  • 使用javax.sound.sampled.Clip播放声音(与sun.audio包中未记录的类相反)。有关工作源,请参见Java Sound info. page
  • 关于java - 如何在程序中添加背景音乐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18553136/

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