How to get one audio track to stop playing when another starts playing (Minim)

edited December 2016 in Library Questions

I have two soundtracks- one named rain and another named heartbeat. The goal is to trigger these audio files when a key is pressed. My problem is that I need to ensure that when one is playing the other stops, and for some reason processing isn't recognizing the .stop() or .pause() functions.

I'm only a beginner with code, so if anyone can let me know what I'm doing wrong/how I can fix this, I'd appreciate it a lot!

    import ddf.minim.spi.*;
    import ddf.minim.signals.*;
    import ddf.minim.*;
    import ddf.minim.analysis.*;
    import ddf.minim.ugens.*;
    import ddf.minim.effects.*;

    Minim minim;
    AudioPlayer heartbeat;
    AudioPlayer rain; 

    void setup()
    {
      size(400, 600);
      minim = new Minim(this);
      heartbeat = minim.loadFile("heartbeat.mp3");
      rain = minim.loadFile("rainforest.mp3");
    }

    void draw() {
      background(0);
      stroke(255);
    }

    void keyPressed() {
      if (key == 'h') {
        heartbeat.rewind();
        heartbeat.play();
        if (key == 'p') {
            heartbeat.pause(); }
      }
       if (key == 'r' && !rain.isPlaying()) {
        rain.rewind();
        rain.play();
        if (key == 's') {
            rain.pause(); }
      }
    }

Answers

  • Do not post the same discussion more than once! I have deleted the copy.

  • edited December 2016 Answer ✓

    indenting your code properly shows a problem

    void keyPressed() {
      if (key == 'h') {
        heartbeat.rewind();
        heartbeat.play();
        if (key == 'p') {
          heartbeat.pause();
        }
      }
      if (key == 'r' && !rain.isPlaying()) {
        rain.rewind();
        rain.play();
        if (key == 's') {
          rain.pause();
        }
      }
    }
    

    heartbeat.pause() is only called if key == h AND if key == p... can never be true. same for rain.pause()

    you might want to move those two conditions outside of the two outer conditions.

  • Answer ✓

    or, if you want one to stop when the other starts then put rain.pause() after heartbeat.play() and heartbeat.pause() after rain.play()

  • That worked, thank you so much!

Sign In or Register to comment.