Buzzer ON and OFF

I am trying to make a little song and I want it to start when Button A is pressed and to Stop in every moment when button B is pressed. And after hours of searching I have not found a solution.
Here is what I have tried:

#defined notes

int chorus[] = {

int buttonState1 = 0;
int buttonState2 = 0;

int buzzerPin = 8;
int buttonA = 2;
int buttonB = 4;

void setup()
  pinMode(buttonA, INPUT);
  pinMode(buttonB, INPUT);
  pinMode(buzzerPin, OUTPUT);

void loop() {

  buttonState1 = digitalRead(buttonA);
  buttonState2 = digitalRead(buttonB);

  if (buttonState1 == 1){
    for (int i = 0; i < 9; i++) {
    tone(buzzerPin, chorus[i], 500);

 if (buttonState2 == 1){


Is it possible to make it?

I'm not exactly sure what "stop in every moment" means but try putting your test for buttonState2 INSIDE the for loop that is playing the tune. Then you can either play a tone() or a notone().


When you press the button A the song starts. But I can not stop it until the whole code was read. And I wanted to stop the Loop in every moment by pushing the button B.

You are only acting on button2 after the song is done. To be able to stop the song while the song is playing you must check the state of the button and act on the button state while the song is playing.
So. like slipstick said, put the button reading and action inside of the for loop.

You use the version of tone that includes duration.
What happens if you do this?

  if (buttonState1 == 1){
    for (int i = 0; i < 9; i++) {
    tone(buzzerPin, chorus[i], 500);
//    delay(500);
//    noTone(buzzerPin);

I have used all the tips but doesn't works like I wanted. But it helped me solve another problem for resting the song.

You need to look into millis() timing to get rid of the delay().

Your code will get fast enough to read button bouncing (sparks crossing the tiny gap at switch close and open) that you will have to use code or a capacitor to fix.

Both things are shown how-to-do here.