java - 使用 Swing 计时器以特定模式触发事件

标签 java swing audio timer

我正在构建一个鼓机/音序器应用程序,用户在其中选择一种复选框模式(采用网格格式:每列是不同的节拍,每行是不同的乐器),并且在单击“播放”时,音频样本应该在模式中的每个选定节拍上播放。

目前,我正在使用 java.swing 计时器来循环运行 note() 方法。然而,这使得它在每个“节拍”上播放,而我只希望它在选定的节拍上播放。我有一种感觉,我需要在某个地方使用timer.stop()和timer.start(),这样note()就不会在未选择的节拍上执行,但会在遇到下一个选定的节拍时重新开始。

我创建了数组 int pattern[] = {1,0,1,0}; 来保存我想要播放声音的模式。我在想可能有一种方法可以循环遍历数组并在每次值为 1 时执行 note(),但我真的不知道该怎么做。

所以我想主要问题是:如何让计时器触发(或不触发)模式中的事件?我的任何倾向是正确的,还是我以错误的方式处理这个问题? 感谢您的任何建议/意见:)

这是我到目前为止所拥有的:

import java.io.*;
import javax.sound.sampled.*;
import javax.swing.Timer;
import java.awt.event.*;

public class PlaySound extends JFrame {

static String folderPath = "folder/path/goes/here/";
public static String fileName = "kick_01.wav";
int pattern[] = {1,0,1,0};
int c = 0;

   // Constructor
   public PlaySound() {
       Timer timer = new Timer(500, new ActionListener() { //500 == 120bpm
           public void actionPerformed(ActionEvent e) {
               note(fileName); //Play audio file
       }
   });
   timer.start();
   }

   public static void note(String f) {
   try {
       try {
             // Open an audio input stream.
             File soundFile = new File(folderPath + f);
             AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
             // Get a soundjava 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();
          }
   } catch (Exception e) {}
   }

}

最佳答案

每次计时器触发时,跟踪您在模式中的位置。像这样的东西:

if (pattern[index] == 1)
    playSound();

index++;

if (index == pattern.length)
    index = 0;

关于java - 使用 Swing 计时器以特定模式触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9231665/

相关文章:

java - 无法保存到 JBoss 5.1 中的公共(public)配置

java - JFileChooser 不显示应用过滤器的文件

java - 无法将第二个 JLabel 添加到单个 JWindow 中的第二个 JPanel

java - Eclipse 新文件夹需要父文件夹

objective-c - 识别低频噪声中短促的高频声音(objc/c)

java - 组件的宽度属性意外更改

java - 图像未显示在可执行 jar 中

java客户端服务器端socket编程实现问题

ios - AVPlayer 停止播放并且不会再次恢复

google-app-engine - 如何将在线生成的音频上传到Google App Engine Blob存储