gpt4 book ai didi

java - 如何在按下按钮时循环播放声音并在释放时停止播放?

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

我试图搜索与此类似的问题,但找不到。我不知道在释放按钮时如何停止声音,而且我也不知道如何仅一个一个地循环播放声音,当我按住按钮时,它会在上一个循环仍在播放的同时再次播放声音从∞声音变成一个循环。

这是代码:

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class test {

String b[]={"Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"};
Action[] actions = new AbstractAction[26];

public test() throws Exception {

JFrame frame = new JFrame();

JButton[] buttons = new JButton[26];

for(int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(b[i]);
buttons[i].setSize(80, 80);
buttons[i].addKeyListener(new KeyAdapter(){

public void keyPressed(KeyEvent e){
System.out.println(e.getKeyChar());
playSound(new File("loopbase/loop1/"+e.getKeyChar()+".wav"));
}

public void keyReleased(KeyEvent e){

}

});
frame.add(buttons[i]);
}

JPanel contentPane = (JPanel)frame.getContentPane();

frame.setLayout(new GridLayout(3, 5, 5, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
try {
new test();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

}

public void playSound(File soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundName.getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}

}

有人可以帮我解决这个问题吗?

最佳答案

I don't know how i can stop my sound when button is released?



您可以使用 DataLine#stop()停止剪辑。只需保留最后播放的剪辑的引用,然后在行下方停止即可。
clip.stop();

注意:您可以将其存储在 static变量中的某个位置。

样例代码:
private static Clip clip;

...
public void keyReleased(KeyEvent e) {
if (clip != null) {
clip.stop();
}
}
...

public void playSound(File soundName) {
...
clip = AudioSystem.getClip();
...
}

关于java - 如何在按下按钮时循环播放声音并在释放时停止播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23249399/

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