如何让一个声音在Processing中播放一次?

How to let a sound play once in Processing?

import processing.serial.*;
import processing.sound.*;

SoundFile file;
Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port
//String antwoord = "A";
void setup()
{
  size(300,300);
  // I know that the first port in the serial list on my mac
  // is Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  if ( myPort.available() > 0) 
  {  // If data is available,
  val = trim( myPort.readStringUntil(ENTER) );
       // read it and store it in val
  } 
//println(val); //print it out in the console
file = new SoundFile(this,"Promise.mp3");

if ("A".equals(val) == true && file.isPlaying() == false) {
 

file.play();
file.amp(0.2);}

else{
 ellipse(40,40,40,40);
}
}

我得到了这段代码,但我希望只要给出信号 'A',声音就会一直播放。现在它开始不断播放,这会导致奇怪的静态噪音。怎样才能让它稳定播放?

您正在 draw 的每个 运行 中创建一个新的 SoundFile。所以 file.isPlaying() 总是 return false。如果您还没有创建新的 SoundFile。最简单的解决方案可能是将 file = new SoundFile(this,"Promise.mp3"); 移动到 setup

或者您检查或记住您是否已经加载了该文件。

很抱歉,如果它有点断开,但我建议使用 minim 或不同的声音库而不是处理声音库,因为它在导出时会导致很多问题(至少它对我来说一直如此) .