gpt4 book ai didi

java - 如何使用java播放声音

转载 作者:行者123 更新时间:2023-12-01 15:45:32 25 4
gpt4 key购买 nike

我正在尝试在java中单击按钮时播放声音(a.mp3)。

我尝试了这段代码

AudioPlayer.player.start(new FileInputStream(new File("E://a.mp3")));

但是声音不清晰......

我该怎么办,(我是java初学者)。

最佳答案

   **For Playing sound in java, please refer to the following code.**

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 {

// Constructor
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("filenamme.mp3");
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();
}
}

关于java - 如何使用java播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7102316/

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