Quantcast
Channel: Library Questions - Processing 2.x and 3.x Forum
Viewing all 2896 articles
Browse latest View live

Verlet Physics, Simulation of rigid body with complex geometry

$
0
0

Hello there, I am trying to make a body with complex geometry move with gravity. For this I created a grid of particles that all are "attached" to each other with springs and have gravity behaviour. However the result I am getting is a very 'jumpy' geometry that is malleable and jell-like, instead of the rigid body I need. I guess the way to solve this problem is by changing the parameters of my spring (in the ComplexBody class). Any ideas about what I can do?

Here's the code:

import toxi.physics2d.*;
import toxi.physics2d.behaviors.*;
import toxi.geom.*;

VerletPhysics2D physics;

MyPolygon mypolygon;
ComplexBody complexbody;

PVector anchorPoint;
PVector massCenter;

//POLYGON
PVector[] points;
float shapeScale=2;

int gridScale=12;
int rows=25;
int cols=25;

//RECT
int w=460;
int h=90;
int xRect=0;
int yRect=0;


void setup() {
  size(600, 400, P2D);
  smooth();
  //frameRate(30);

  //VERLET PHYSICS
  // Initialize the physics
  physics=new VerletPhysics2D();
  physics.addBehavior(new GravityBehavior(new Vec2D(0, 0.1)));

  // This is the center of the world
  Vec2D center = new Vec2D(width/2, height/2);
  // these are the worlds dimensions (50%, a vector pointing out from the center in both directions)
  Vec2D extent = new Vec2D(width/4, height/4);

  // Set the world's bounding box
  physics.setWorldBounds(Rect.fromCenterExtent(center, extent));


  //POLYGON
  anchorPoint=new PVector(width/2, height/2);

  points=new PVector[8];
  points[0]= new PVector(0,  0);
  points[1]= new PVector(-50, 0);
  points[2]= new PVector(-50, -10);
  points[3]= new PVector(-75, -20);
  points[4]= new PVector(-75, -40);
  points[5]= new PVector(+25, -40);
  points[6]= new PVector(+25, -20);
  points[7]= new PVector( 0, -10);

  for(PVector a: points){
    a.mult(shapeScale);
    a.add(anchorPoint);
  }

  mypolygon=new MyPolygon(points);
  mypolygon.createGrid();
  massCenter= mypolygon.centerOfMass();

  complexbody= new ComplexBody(mypolygon.grid);
}



void draw() {
  background(0);
  physics.update();




  mypolygon.drawGrid();
 // mypolygon.drawGridTwoD();
  mypolygon.drawInitialShape(50);

  complexbody.display();
  complexbody.createSprings();

  fill(0, 100, 255);
  ellipse(massCenter.x, massCenter.y, 10, 10);

}


class ComplexBody {

  ArrayList<Particle> particles;
  ArrayList<PVector> p;

  ArrayList<VerletSpring2D> springs;

  AttractionBehavior repulsion;

  ComplexBody(ArrayList<PVector> p_) {
    p=p_;
    particles=new ArrayList<Particle>();
    springs=new ArrayList<VerletSpring2D>();
    for (int i=0; i<p.size(); i++) {

      PVector a=p.get(i);
      Particle k= new Particle(a.x, a.y);
      particles.add(k);
      physics.addParticle(k);
    }
  }


  void createSprings() {

    for (int i=0; i<particles.size(); i++) {

      Particle s1=particles.get(i);
      //stroke(255);
      //strokeWeight(1);
      //line(s1.x, s1.y, s1.x+10, s1.y+10);

      for (int j=0; j<particles.size(); j++) {

        if (j!=i) {
          Particle s2=particles.get(j);

          stroke(255,10);
          strokeWeight(1);
          line(s1.x, s1.y, s2.x, s2.y);

          float r= dist(s1.x, s1.y, s2.x, s2.y);
          VerletSpring2D spring=new VerletSpring2D(s1, s2, r, 1);
          physics.addSpring(spring);
        }
      }
    }
  }


  void display() {
    for (Particle p : particles) {

      p.display();
    }
  }
}

class MyPolygon {

  float xAverage;
  float yAverage;

  PVector origin;
  PVector location;

  java.awt.Polygon p;
  PVector[] pts;
  ArrayList <PVector> grid;

  MyPolygon(PVector[] pts_) {
    pts=pts_;
    grid=new ArrayList<PVector>();

    p = new java.awt.Polygon();
    for (PVector a : pts) {
      p.addPoint(int(a.x), int(a.y));
    }
  }

  void createGrid() {

    for (int i=-rows; i<=rows; i++) {
      for (int j=-cols; j<=cols; j++) {
        PVector k=new PVector(anchorPoint.x+ (i*gridScale), anchorPoint.y + (j*gridScale));
        if (p.contains(anchorPoint.x+ (i*gridScale), anchorPoint.y + (j*gridScale))) {
          grid.add(k);
        }
      }
    }
  }

  void drawGrid() {

    fill(0, 0, 200, 200);
    noStroke();
    for (PVector v : grid) {
      ellipse(v.x, v.y, 2, 2);
    }
  }


  PVector centerOfMass() {
    int xcount=0;
    int ycount=0;


    for (int i=0; i<grid.size(); i++) {
      xcount+=grid.get(i).x;
      ycount+=grid.get(i).y;
    }

    xAverage=xcount/grid.size();
    yAverage=ycount/grid.size();

    PVector r=new PVector (xAverage, yAverage);
    return r;
  }


  void drawInitialShape(float alpha) {

    fill(255, alpha);
    beginShape();
    for (PVector a : points) {

      vertex(a.x, a.y);
    }
    endShape();
  }
}

class Particle extends VerletParticle2D {

  Particle(float x, float y) {
    super(x,y);
  }

  void display() {
    fill(255);
    noStroke();
    ellipse(x,y,2,2);
  }
}

problem with cam.start(); error line ( Tread.java:745) on Mac Mini i5

$
0
0

Hi All,

I am still working on the same project, but is going to use Mac mini i5 2012 to run the program I found out that the camera.start(); is causing the problem now. The error says:

java.lang.RuntimeExcaption: Waited 5000ms for: <365779eb, 38909151>[count 2, qsz 0, owner <main-FPSAWTAnimator#00-Timer0>] - <main-FPSAWTAnimator#00-Timer1>

at processing.opengl.PSurfaceJoGL$2.run(PSurfaceJPGL.java:467) at java.lang.Thread.run(Thread.java:745)


When I use this find with MBP it is fine, so I wonder how should I change the line or where to place it to run the program again. Also, I read somewhere to use delay();, which I did try but didn't work.

Any suggestion?? Thanks

Library for displaying geographic maps?

$
0
0

I am looking something like google maps API but for processing 3. I have some geolocation data and I want to display the corresponding map. I learnt about Unfolding and googlemapper but unfortunately are outdated and work only with processing 2.It is important for me to use processing 3. Any ideas?

Draw blob edges that are on edge of sketch

$
0
0

Hi, I've been working at making contour maps using the blobDetection library; everything has gone fine till here, I can get the contours and everything.

Now I am exporting each layer as an SVG and I see that the four edges of the sketch are always blank. In other words, I want blobs that go over the edge of the sketch to have strokes joining both sides of that blob, instead of having sort of an "incomplete blob".

Here is the code:

import processing.svg.*;

import blobDetection.*;
import peasy.*;
import processing.pdf.*;
PeasyCam cam;

PImage img;

float levels = 3;
//float factor = 1;      //Scale factor, not used.
//float elevation = 50;  //Not used.

BlobDetection[] contours = new BlobDetection[int(levels)];

//Creating array to store the blob objects
ArrayList<Ring> rings = new ArrayList<Ring>();

void setup() {

  size(480, 360, P3D);
  surface.setResizable(true);

  img = loadImage("map1.gif");
  surface.setSize(img.width, img.height);

  cam = new PeasyCam(this, img.width, img.height, 0, 1500);
  colorMode(HSB, 360, 100, 100);

  for (int i=0; i<levels; i++) {
    contours[i] = new BlobDetection(img.width, img.height);
    contours[i].setThreshold(i/levels);
    contours[i].computeBlobs(img.pixels);
  }

  for (int i = 0; i < rings.size(); i++) {
    System.out.println("id: " + rings.get(i).getId());
    System.out.println("lvl: " + rings.get(i).getLvl());
    System.out.println("x: " + rings.get(i).getX());
    System.out.println("y: " + rings.get(i).getY());
    System.out.println();
  }
  noLoop();
}


void draw() {

  for (int i=0; i<levels; i++) {

    beginRecord(SVG, "level-"+i+".svg");

    drawContours(i);
    println("drew level " + i);

    println("saved as: level-"+i+".svg");
    endRecord();
    println();

    if(i == levels-1){
      println("finished");
    }

  }


}

void drawContours(int i) {
  Blob b;
  EdgeVertex eA, eB;
  for (int n=0; n<contours[i].getBlobNb(); n++) {
    b=contours[i].getBlob(n);

    if (n==0){
      b2 = b;
    }
    else {
      b2 = contours[i].getBlob(n-1);
    }

    //Condition for drawing only blobs bigger than 5% of width and 5% of height
    if(b.w*width>.05*width && b.h*height>.05*height){

      if (b!=null) {
        stroke(250, 75, 90);

        for (int m=0; m<b.getEdgeNb(); m++) {
          eA = b.getEdgeVertexA(m);
          eB = b.getEdgeVertexB(m);

          if (eA !=null && eB !=null)
           line(
           eA.x*img.width, eA.y*img.height,
           eB.x*img.width, eB.y*img.height
           );

           // // // // // //

           /*
           *Here is where I attempt to test if an EdgeVertex is touching any border of the sketch
           *Note: x and y are properties of the blob object and are scaled from 0 to 1. So I test
           *if x or y equal 0 or 1.
           *Note: For testing simplicity, I check only for x=0 in this code
           */

           if (b.getEdgeVertexA(m).x == 0 && b.getEdgeVertexB(b.getEdgeNb()).x == 0){

                 line(  eA.x*img.width, eA.y*img.height,
                        eB.x*img.width, eB.y*img.height   );

                 println("////");
                 println("making line");
                 println("////");
           }

           // // // // // //

        }

        //Adding objects to the rings ArrayList
        rings.add(new Ring(String.valueOf(rings.size()+1), (int) i, (double) b.x*100, (double) b.y*100));

        }
    }
  }
}

Just to reemphasize what I write as a comment in the code: I am trying to check if any vertex of the blob has coordinates that touch the borders of the sketch. Ideally, if that condition is met, the program should draw lines that would join each edge of the blob. I am not there yet... so if you have any suggestions, comments on my code, etc. I'd be glad to hear.

Thanks

recording a video

$
0
0

Hello,

I wrote a programme for audio-reactive visuals … usually I perform live in clubs (like here), but this time I need to record a video (sound doesn’t matter). I tried to write out jpegs, and a screen capture with Quicktime, but both slows down the programme a bit. However it is pretty essential that the visuals react precisely to the audio.

Does anybody have some advice maybe?

Cheers!

send text message to a sketch

$
0
0

I would love to write a programme that displays short messages from users, and I thought a possibility would be a library that allows to receive sms.

I did find a library called smsP5, but I can’t find any documentation on how to connect the sketch to a phone or server?

The example says:

org.apache.log4j.BasicConfigurator.configure(); receiver = new ReceiveSms("modem.com1", "COM3", 19200,"Huawei", "E220",3);

Not sure what to do with this. :-/

It would be amazing if anybody could share some experience or point me towards a tutorial. I guess other popular messaging services or e-mails could be a possibility as well.

Thanks so much!

MJPEG Capture

$
0
0

Hi, I'm hoping to capture feeds from 4 usb webcams that output in MJPEG format. I haven't bought them yet hence I can't just try it out myself.

I saw this open issue on the processing video github https://github.com/processing/processing-video/issues/46 - The person says they can't access the MJPEG version of the stream even though it's listed in the available cameras. There's very little detail though, has anyone else managed to stream MJPEG at 30+fps from a webcam using capture()?

Alternatively, is anyone is using the capturemjpeg library with processing 3.x on mac https://bitbucket.org/nolith/capturemjpeg/wiki/Home - It doesn't seem to have been updated in a while but I saw it recommended on here in a post from 2015 - https://forum.processing.org/two/discussion/11247/apache-commons-io

If it's not possible to stream MJPEG easily in processing would I be better off trying to find webcams that output a h.264 stream? Or maybe use gstreamer to capture the video, re stream it via localhost and pick it up with IPCapture. Just looking for some input before I make a worthless purchase!!

Thanks!

How to read and understand serial data?

$
0
0

I am trying to connect my Neurosky EEG sensor with processing code without using ThinkGear connector. ThinkGear connector is an application which read serial data and transmit over WebSocket so that other application can listen to that WebSocket and use the data. It transmit data like eSense, raw, eyeblink (single) as JSON.

Problem - Using websocket I can connect with the device and receive JSON data but this JSON doesn't contain double eye blink data which is really crucial for me hence I want to write my own ThinkGear like emulator in processing.

PROBLEM PART 1

I have been tying to read serial data using processing and I was successful but now I don't know how to interpret this data. I have been trying to read ThinkGear communication protocol but everything was going over my head. I hope someone will help me to fill this :) :)

PROBLEM PART 2

I don't understand the use of myPort.buffer(12);. Also what is the point of setting byte[] inBuffer = new byte[8] if it is going to take buffer size as set in the beginning with myPort. What is the point of using myPort.readBytes(inBuffer); when inBuffer give the same values as without using readBytes(). Why myPort.buffer(size) affect the byte[] size even though I hardcoded it to 8 and how come it is taking 12 values even after hardcoding byte[] size to 8?

CODE

    import processing.serial.*;
    Serial myPort;  // Create object from Serial class
    String myString="";
    String arrayval="";

    byte[] inBufferfinal = new byte[12];
    void setup() {
      size(600, 400);
      String[] portName = Serial.list();
      for (int i=0; i<portName.length; i++) {
        if (portName[i]!=null) {
          myPort = new Serial(this, portName[i], 9600); // baudrate: 57600, 9600, 115400
          myPort.buffer(12);
          println(portName[i]  + " " + i);
        }
      }
      //frameRate(4);
    }

    void draw() {
      background(255);
      visualizer(12, inBufferfinal );
      fill(0);
      //textAlign(CENTER);
      //text(myString, width/2, height/2);
    }

    void serialEvent(Serial myPort) {
      myString = "";
      arrayval = "";
      byte[] inBuffer = new byte[8];
      while (myPort.available () > 0) {
        inBuffer = myPort.readBytes();
        myPort.readBytes(inBuffer);
        inBufferfinal = inBuffer;
        println(inBuffer, inBuffer.length);
        if (inBuffer != null) {
          for (int i=0; i<inBuffer.length; i++) {
            myString = myString + hex(inBuffer[i])+" , " ;
            arrayval = arrayval+ i +  " , ";
          }
        }
      }
    }

    void visualizer(int lengthofbyte, byte[] val) {
      noStroke();
      fill(0);
      for (int i=0; i<lengthofbyte; i++) {
        int h = val[i];
        rect(230, i*20+20, h, 20);
        text(h, 20, i*20+40);
      }
    }

G4P Limiting User Input

$
0
0

Hello @quark, sorry for bothering again,

I wish to limit whatever the user input into a text field. In the attached image, I attempted to limit the user input of txt_defHPBS, which corresponds the field with the value 5.0.

Every time there is a change in the text field, I grab the string, convert it to a float and adjust it within the value range of 0 to 500, and set it back to display again. Initially, it worked fine, but after a few attempts where I randomly input something into the text field, the program crashes with the exception shown in the screenshot. It happens every time I try to run the sketch.

I was hoping that the user can only input integers or floats, within a range of 1 to 500. I have a feeling that might not be the best approach, what would be your advice? Thanks!

How do you implement frequency modulation using the Sound Library?

$
0
0

I'm new to the "sound" library. I've seen the examples for additive synthesis, but have not found any examples showing the implementation of frequency modulation. Does it have anything to do with the .add(add) method? Would appreciate any help and/or pointers to existing code that might give me some clues. Thanks so much.

How do you add an image??

$
0
0

Hi my name is Helen I have only just recently started using Processing & I am still unable to add an image even though I followed a Processing guide. I was wondering whether anyone would be able to help & inform me on the coding needed for adding an image onto a program/game made using Processing.

Many Thanks

Helen

How to change permission in terminal I cannot use VideoExport Library.

$
0
0

Hi guys,

I have a problem trying to use any of the code from the library of Video Export that they get the same error.

Even with the code from the website itself here > http://funprogramming.org/VideoExport-for-Processing/#examples ,

I also get error with permission thing.

say:

java.io.IOException: Cannot run program "/Users/Tuang/Desktop/DMA_WORKS/Work1_Facial Muscles/Cam_Rec/sketch_161027a/sketch_161027a.pde": error=13, Permission denied
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at com.hamoid.VideoExport.startFfmpeg(Unknown Source)
    at com.hamoid.VideoExport.initialize(Unknown Source)
    at com.hamoid.VideoExport.saveFrame(Unknown Source)
    at sketch_161027b.draw(sketch_161027b.java:51)
    at processing.core.PApplet.handleDraw(PApplet.java:2412)
    at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1540)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)
Caused by: java.io.IOException: error=13, Permission denied
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 7 more
VideoExport error: Ffmpeg failed. Study /var/folders/nq/xsfvm25d249181txfc2_c39c0000gn/T/untitled6197566133901091867sketches/sketch_161027b/camera.mp4.txt for more details.
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help → Troubleshooting.

So I google

1) how to change permission -> which I found that my Mac cannot find the file it said there is no such file.

2) how to find a file in Mac with terminal -> later I found that it is about the space bar in a folder name, so I changed it.

Then, I was able to find a file and I guess I've already changed the permission with chmod 777, since I typed it in and has no error with finding the file thing. However, back to the Processing the same error still there.

3) Do I have FFmpeg ->Terminal said, it cann't find it so I download two versions and installed one but didn't work so try installed another, still didn't work.

Now.. I don't know what to do. Please help! The error still here.

Emotion API and POST and HTTP requests library

$
0
0

Hi all.

I have tried to resolve this to no avail. I just don't know what I'm doing wrong. I really hope someone out there can point me in the right direction. Apologies if my use of terminology is occasionally bogus below - network stuff is not my usual bag.

Basically, I'm trying to use the Microsoft Emotion API in Processing: https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/563b31ea778daf121cc3a5fa It requires API key authentication and HTTP headers as a POST request. I found the HTTP requests library (by Shiffman et al) which apparently takes the pain away (heh) and built a test example below:

import http.requests.*;
PostRequest post;

void setup() {
  size(400, 400);
  makeRequest();
  //println("Reponse Content: " + post.getContent());
  //println("Reponse Content-Length Header: " + post.getHeader("Content-Length"));
  JSONObject response = parseJSONObject(post.getContent());
  println(response);
}

void makeRequest() {
  post = new PostRequest("https://" + "westus.api.cognitive.microsoft.com/emotion/v1.0/recognize");
  post.addHeader("Content-Type", "application/json");
  post.addHeader("Ocp-Apim-Subscription-Key", MyAPIkeyGoesHere);
  post.addData("url", "http://" + "www.boro.gr/contentfiles_2016/psyxologia/thymos/axaaamm.jpg");
  post.send();
}

What I should get back is a JSON file that looks like this:

  {
    "faceRectangle": {
      "height": 216,
      "left": 225,
      "top": 90,
      "width": 216
    },
    "scores": {
      "anger": 9.38430444E-11,
      "contempt": 3.36862873E-12,
      "disgust": 4.649468E-11,
      "fear": 1.913897E-11,
      "happiness": 1.0,
      "neutral": 7.306441E-11,
      "sadness": 1.65613755E-11,
      "surprise": 2.97461256E-09
    }
  }

... but what I get is this:

{"error": {
  "code": "BadBody",
  "message": "JSON parsing error."
}}

Anybody know what's going on? Also, if I was wanting to upload an image locally, how would I do that? Apologies for lameness, but am very grateful for any help. Thanks.

Kind regards, Paul.

How do I layer video over images?

$
0
0

I've written a program that displays 3 random image loops and plays some audio. That part is all fine. However, when the audio finishes I want to stop everything, play a short video and then exit the program. The audio from the video is playing, and the program exits at the right time, but the video appears to be either hidden behind the images or not playing properly. Can't find anything about this after multiple searches... Here is the code:

GlitchObject myGlitch;
boolean glitch = true;
PImage [] imagesbg;
int numImagesbg = 14;
int counterbg = 0;

PImage [] imageshl;
int numImageshl = 45;
int counterhl = 15;

PImage [] images;
int numImages = 65;
int counter = 46;

import processing.video.*;
Movie turnoff;

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

import ddf.minim.*;
Minim minim;
AudioPlayer song1;




void setup() {
  size(1440, 900);
  frameRate(10);

  minim = new Minim(this);
  song1 = minim.loadFile("Project Audio2.mp3");

  imageshl = new PImage[numImageshl];
  for (int i=15; i<numImageshl; i++) {
    imageshl[i] = loadImage( str(i)+".png" );
  }

  images = new PImage[numImages];
  for (int i=46; i<numImages; i++) {
    images[i] = loadImage( str(i)+".png" );
  }


  imagesbg = new PImage[numImagesbg];
  for (int i=0; i<numImagesbg; i++) {
    imagesbg[i] = loadImage( str(i)+".png" );
  }

  myGlitch = new GlitchObject();

  turnoff = new Movie(this, "TV Static Turn Off Effect.mov");
}



void draw() {

  song1.play();
  noLoop();



  image(imagesbg[counterbg], 0, 0);
  counterbg++;
  if (counterbg>=numImagesbg) {
    counterbg=0;
  }

  if (frameCount % 40 == 0 || frameCount == 0) {
    counterhl = (int)random(15, 45);
  }
  image(imageshl[counterhl], 50, 500);


  if (counterhl>=numImageshl) {
    counterhl=15;
  }

  if (frameCount % 40 == 0 || frameCount == 0) {
    counter = (int)random(46, 65);
  }
  image(images[counter], 750, 400);

  if (counter>=numImages) {
    counter=46;
  }
  if (glitch) {
    myGlitch.run();
  }
  if (frameCount % 50 == 0) {
    background(0);
    turnoff.play();
    song1.pause();
  }
  if (frameCount % 75 == 0 || frameCount == 0) {
    exit();
  }
}

I haven't included the GlitchObject code cos I don't think it's relevant, but I can post if you think it is...

Serial library - catch port busy

$
0
0

Hi,

I work with a bluetooth serial device and I regularly get the message: Error opening serial port... : Port Busy.

When I retry a few times I can get a connection. Is there a way that I can catch the error in my program itself and retry the connection.

So when this happens I could run something like:

port.clear();
port.stop();
port = new Serial(this, Serial.list()[portNumber], 9600);
port.clear();

How do you implement java.awt.robot into a sketch?

$
0
0

I have been using this code below in my sketch, but it causes processing to stop when it is combined with serial communication to an arduino... The serial part of my sketch works fine as long as I remove all of the code below... if I leave it in, it will error out about 4 out of 5 times... then work fine until I run it again... Is there a chance that I am not setting up the robot class correctly or that the serial class is wrong but somehow works because robot isnt there???

import java.awt.Robot;
import java.awt.AWTException;
Robot robby;
void setup()
{

//robot setup
   try
    {
      robby = new Robot();
    }
    catch (AWTException e)
    {
      println("Robot class not supported by your system!");
      exit();
    }
  robby.mouseMove(screenResX/2, screenResY/2); //test line to move cursor
}

Using a sound input to affect text.

$
0
0

I'm trying to self teach the Processing language, and struggling with something I'm trying to do for university.

This is probably quite simple for someone who knows what they're doing... I'm trying to use sound input to change the opacity of text. The louder the sound, the greater the opacity. Could someone help with the coding?

Many thanks hope someone can help!

How/where do I alter output (minim, reverb)

$
0
0

looking to add reverb to the keyboard, do not know how to add this effect can anybody help

import ddf.minim.analysis.*;
import ddf.minim.*;
import ddf.minim.signals.*;

Minim minim;
AudioOutput out;

void setup()
{
  size(512, 200, P3D);

  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
}

void draw()
{
  background(0);
  stroke(255);
  for(int i = 0; i < out.bufferSize() - 1; i++)
  {
    float x1 = map(i, 0, out.bufferSize(), 0, width);
    float x2 = map(i+1, 0, out.bufferSize(), 0, width);
    line(x1, 50 + out.left.get(i)*50, x2, 50 + out.left.get(i+1)*50);
    line(x1, 150 + out.right.get(i)*50, x2, 150 + out.right.get(i+1)*50);
  }
}

void keyPressed()
{
  SineWave mySine;
  MyNote newNote;

 float pitch = 0;
  switch(key) {
    case 'z': pitch = 262; break;
    case 's': pitch = 277; break;
    case 'x': pitch = 294; break;
    case 'd': pitch = 311; break;
    case 'c': pitch = 330; break;
    case 'v': pitch = 349; break;
    case 'g': pitch = 370; break;
    case 'b': pitch = 392; break;
    case 'h': pitch = 415; break;
    case 'n': pitch = 440; break;
    case 'j': pitch = 466; break;
    case 'm': pitch = 494; break;
    case ',': pitch = 523; break;
    case 'l': pitch = 554; break;
    case '.': pitch = 587; break;
    case ';': pitch = 622; break;
    case '/': pitch = 659; break;
  }

   if (pitch > 0) {
      newNote = new MyNote(pitch, 0.2);
   }
}

void stop()
{
  out.close();
  minim.stop();

  super.stop();
}

class MyNote implements AudioSignal
{
     private float freq;
     private float level;
     private float alph;
     private SineWave sine;

     MyNote(float pitch, float amplitude)
     {
         freq = pitch;
         level = amplitude;
         sine = new SineWave(freq, level, out.sampleRate());
         alph = 0.9;
         out.addSignal(this);
     }

     void updateLevel()
     {
         level = level * alph;
         sine.setAmp(level);

         if (level < 0.01) {
            out.removeSignal(this);
         }
     }

     void generate(float [] samp)
     {
         sine.generate(samp);
         updateLevel();
     }

    void generate(float [] sampL, float [] sampR)
    {
        sine.generate(sampL, sampR);
        updateLevel();
    }

}

How do i import various videos into one code?

$
0
0

Hello!

I have been trying to import videos into the tutorial code on this link as a basic template to build on https://www.processing.org/reference/libraries/video/Movie.html

however, when i run the file (im importing .mov files), the error message below appears:

"could not run the sketch" it sometimes also tells me it was unable to load the file.

Why could this be? Im confused as the code appears as though it would work with no issues?

tia

Game Control Plus - recognizing a device?

$
0
0

I'm trying to get GCP to work again with a sketch I'm redirecting but struggling to get the library to find any devices on my system. Installed 1.2 library. I run GCP_showDevices and get no results, though there is both keyboard and trackball attached. I presume the library can't get signals from the peripherals if show devices isn't finding them and this is my problem. my sketch did have the layout file for the library to reference from the old sketch, but no matter what I can't seem to locate the trackpad. I must be doing something wrong as it seems that other people have used this recently

I seem to remember this being painful before. I've removed all usb hubs that I can, so not going thru one except in the computer. I seem to recall issues when more than one controller attached too. Tried rebooting....

Not sure where to look next. Perhaps trying to use the actual java libraries?

Viewing all 2896 articles
Browse latest View live