How do i get sound to play on the phone

edited October 2015 in Android Mode

The code below works fine in java mode, but it doesn't work in Android mode. I just want a simple code that will play a mp3 file when clicked. I'm pretty sure the problem is in the import of Minim, I'm guessing it doesn't work for Android. If that is the case what do I need to use?

import ddf.minim.*; AudioPlayer player; Minim minim;
void setup(){minim = new Minim(this);} void draw(){} void mousePressed() { player = minim.loadFile("sin1.mp3" ); player.play(); } void stop() { player.close(); minim.stop(); super.stop(); }

Answers

  • I believe they made the newest "Sound" library b/c "Minim" isn't compatible w/ Android:
    https://Processing.org/reference/libraries/sound/index.html

  • Okay,

    below is the code i tried based on the link @GoToLopp gave me.

    import processing.sound.*; SoundFile file; void setup(){} void draw() {} void mousePressed() { file = new SoundFile(this, "sin1.mp3"); file.play(); }

    I tried a few variations of that code, but it always crashes when the mp3 file loads.

    I have the file on my PC in the folded that the code is it (it works in java mode) and the phone is connected via USB to the PC. Do i need to put the file on the phone or something like that?

    Please help.

  • @rhytmiccycle:: minim does not work with android mode ( perhaps it has changed but i dont know) sound? i dont know android has its own api to play sound : mediaPlayer, it s easy to make working but with processing the most simple way is to use APwidgets lib which wraps the media player class from android (in this case you put your.mp3 in the data folder)

    code snippet:// you must add on destroy() and on stop() and release the player

        import apwidgets.*;
                import android.view.KeyCharacterMap;
                  import android.view.KeyCharacterMap.KeyData;
                  import android.view.KeyEvent;
    
    
                PMediaPlayer player;
                boolean play = false;
                boolean sketchShouldClose = false;
                int state = 0;
    
                void setup() {
    
                orientation (PORTRAIT);
    
                initPlayer();
    
                }
                void draw() {
    
                  if (state == 0){
                    background(255, 0, 0);
                  }else if (state == 1){
                    background(0, 0, 255);
                }
    
                 fill(75);
                 textSize(24);
                 text(player.getDuration(), 50, 100); //display the duration of the sound
                 text(player.getCurrentPosition(), 50, 130); //display how far the sound has played
                }
    
    
                public void onPause(){
                  super.onPause();
                  if(play){
                    player.pause();
    
                    println("je pause");
                    play = false;
                  }
                  }
    
                  public void onResume() {
                    super.onResume();  
    
    
                    if (play == false) {
                      initPlayer();
                        println("again");
    
                    }
                }
    
                private void initPlayer(){
                   player = new PMediaPlayer(this); //create new APMediaPlayer   
                  player.setMediaFile("altastrada.mp3");
    
                  //player.setLooping(true); //if you want to loop
                  player.setVolume(1.0, 1.0);//or 0.5, or...
                        player.start(); 
                        play = true;
                }
    
  • I looked for APwidgets in the "contribution Manager" and nothing came up. So I googled it. And found this site:

    https://code.google.com/p/apwidgets/downloads/list

    I d/l-ed "apwidgets_r44.zip" and unzipped in my librart folder. i see "apwidgets" in my import library menu. So I'm pretty sure I did that part right.

    @akenaton I get to line 7 on the above code and i get the error

    "PMediaPlayer cannot be resolved to a type"

    did I use the wrong library? Do I need to make the class my self?

    (btw: hello again akenaton. What tags do you use to show your code like that? I"m using code, but that is not the same.)

  • I got passed line 7 its, "APMediaPlayer" not "PMediaPlayer"

  • edited October 2015

    I'm trying to isolate the problem. I think its is here:

    import apwidgets.*; APMediaPlayer player; void setup() {
    orientation(PORTRAIT); player = new APMediaPlayer(this); //create new APMediaPlayer player.setMediaFile("test.mp3"); //set the file (files are in data folder) } void draw() { }

    It always acrashes when I load the file. I put test.mp3 in the same folder as the pde file, and I also made a folder called data and put it in there. Either way it crashes.

    I just want a simple code that can play a file. I think the problem might have something to do with where the file is stored. I feel like I need to put the file on the phone, But I have no idea where.

    still can get sound to play on my phone :-<

  • @rhythmiccycle:: as for AP or P:: depends of the version f the lib, at the very beginning it was AP, then it was P, and now, according to what you say it s again AP... no problem! -----as for my version PMediaplayer works (though in the examples which does not work it is AP!!!!) -----files are to put either in data or at the same level than .pde ---- it crashes::: what in the console??? ----what version of processing / android ---- what os?

  • downloaded 44:: AP again!!!

  • &&tried (my code)::: works fine (changing P to AP) i have tested with P5 2.XX, devices samsung galaxy s running gingerbread @@ sony XPeria Z running Lollipop

  • im use samsung s4 running android 5.0.1. I'm running the program on the actual phone via usb (not an emulator) runing windows 7 & 10 (I'm trying this on 2 PCs)

    [quote] files are to put either in data or at the same level than .pde ---- it crashes::: what in the console??? [/quote]

    it crashed on the phone. not the PC

    (btw: how do i get the code and quotes tags to work on this forum)

    @akenaton did you run it on an actual phone or an emulator?

  • @rhytmiccycle== 2 real phones Emulator 4.4 everything runs! what version from processing??? 2XX or 3XX??? --- a lot of libs which run with 2 cannot run with 3 (and APwidgets does not seem to be updated since 2011...) - Yet, i you say that there is no error message when compiling, i am not sure that this could be the reason, but who knows...In case forget APwidgets (which does not work for a lot of things) && try media player class from android itself, easy to use.

  • I agree with akenaton.. Use MediaPlayer directly. The problem with libraries, is that they need regular updating if you rely on them.

  • @hudson_m400:::

    yes && ++ = principle of libs is to make things more simple but when they wrap simple things i don't understand...

  • I'm running processing 3.0b7

    If i run this code it works (the part the opens the file in commented out)

    
    import apwidgets.*;
    APMediaPlayer player;
    void setup() {
    
      orientation(PORTRAIT);
      player = new APMediaPlayer(this); //create new APMediaPlayer
     // player.setMediaFile("test.mp3"); //set the file (files are in data folder)
    }
    void draw() {
      rect(200, 300, 100, 400); //this is like a "hello world"
    }
    

    my phone has a grey screen with a white rectangle in it. If I remove the comment marks on line 7, then run the code It opens for a fraction of a second and then says: "Unfortunately, playSound has stopped" on the phone.

    In processing i get these errors in red. It says some other stuff too, but I think this part has to do with the problem. (if you want to see the full output let me know)

    
    FATAL EXCEPTION: Animation Thread
    Process: processing.test.playsound, PID: 939
    java.lang.NoSuchMethodError: No virtual method getAssets()Landroid/content/res/AssetManager; in class Lprocessing/core/PApplet; or its super classes (declaration of 'processing.core.PApplet' appears in /data/app/processing.test.playsound-1/base.apk)
        at apwidgets.APMediaPlayer.setMediaFile(APMediaPlayer.java:81)
        at processing.test.playsound.playSound.setup(playSound.java:50)
        at processing.core.PApplet.handleDraw(Unknown Source)
        at processing.core.PGraphicsAndroid2D.requestDraw(Unknown Source)
        at processing.core.PApplet.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:818)
    
    

    it says unknown source, so maybe I have in install another library.

  • @you said :: nothing in console... tomorrow i ll see...

  • @akenaton I went back and checked again, and there was errors in the console the whole time. I didn't realize at first. (I'm still stuck )

  • without knowing -- which os (osx or windows) -- which processing version (2XX or 3XX) --which target SDK it s difficult to answer... the error is about the .mp3, which is not found because setMediaFile method (from APwidgets) seems to call (in android) getAssets()in a wrong way, yet as my code runs fine for me i think that os version sdk etc are the problem and i repeat:: leave APwidgets and try to use the mediaPlayer class from android...

  • @akenaton I thought I said this already, but maybe it was in another post. I'm using windows 10 and 7 (I get the same problem on 2 different computers ) and I'm running processing 3. I already tried the media player class, but I'll try it again and post the errors.

    I've been searching all over Google, but I can't find a solution. One forum thread I found processing android mode can't do sound, but you said you can do it, so there must be a way.

    I really appreciate your help.

    (I'm going to try a few things tonight and post what happens )

  • @ rhytmiccycle

    now it s clear

    forget APwidgets use android media player class && be happy

  • @akenaton, I'm trying to look up android media player class. I found a bunch of java code. This is the latest code I've tried that doesn't work:

    
    import android.media.MediaPlayer;
    import android.media.AudioManager;
    MediaPlayer MediaPlayer;
    void setup(){
     MediaPlayer = MediaPlayer.create(this, "test.mp3");
    }
    void draw() {}
    

    then i get a error saying :: create() expects parameters like: create(Context, Uri)

    I don't know what Uri is. I tried looking it up, but I get big sets of java code. I can't find anything that I can make sense of.

    I also tried running this code again:

    
    import processing.sound.*;
    SoundFile file;
    
    void setup() {}      
    void draw() {}
    void mousePressed() {
      file = new SoundFile(this, "sin1.mp3");
      file.play();
    }
    

    and I get the errors:

    FATAL EXCEPTION: Animation Thread
    Process: processing.test.playsoundprogsimp_take2, PID: 12684
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/processing.test.playsoundprogsimp_take2-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libMethClaInterface.so"
        at java.lang.Runtime.loadLibrary(Runtime.java:366)
        at java.lang.System.loadLibrary(System.java:989)
        at processing.sound.MethClaInterface.(Unknown Source)
        at processing.sound.Engine.(Unknown Source)
        at processing.sound.Engine.(Unknown Source)
        at processing.sound.Engine$LazyHolder.(Unknown Source)
        at processing.sound.Engine.start(Unknown Source)
        at processing.sound.SoundFile.(Unknown Source)
        at processing.test.playsoundprogsimp_take2.playSoundProgSIMP_Take2.mousePressed(playSoundProgSIMP_Take2.java:29)
        at processing.core.PApplet.mousePressed(Unknown Source)
        at processing.core.PApplet.handleMouseEvent(Unknown Source)
        at processing.core.PApplet.dequeueEvents(Unknown Source)
        at processing.core.PApplet.handleDraw(Unknown Source)
        at processing.core.PGraphicsAndroid2D.requestDraw(Unknown Source)
        at processing.core.PApplet.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:818)
    

    I just want a simple program the can play an mp3 with very little code. I don;t want any button or anything like that.

  • Uri uri means :: the path to the file context: import Context from android Context c = getApplicationContext(); but i can give you some snippet for that if you want.

  • edited October 2015

    quickly done but tested::

                import java.io.File;
                import java.io.IOException;
                import android.media.MediaPlayer;
                import android.media.MediaPlayer.OnPreparedListener;
                import android.content.res.AssetFileDescriptor;
    
                /////////////////////////////////////////////////////////
    
                MediaPlayer mp;
                public boolean loop = true;
    
    
                void setup(){
                  orientation(PORTRAIT);
                  background(255,0,0);
                  fill(255);
                  textSize(24);
                  text("SONG IS PLAYING", 200,300);
    
                 mp = new MediaPlayer(); 
    
                try {
                AssetFileDescriptor afd = getAssets().openFd("myp3.mp3");//which is in the data folder
                mp.setDataSource(afd.getFileDescriptor());
                mp.prepare();
                } catch(IOException e) {
                //Todo
                  }
                   mp.setLooping(loop);
                  mp.start();
    
    
                };
    
                void draw(){
    
                };
    
         public void pause(){
        super.pause();
        if (mp !=null){
        mp.release();
        mp = null;
        }
        };
    
                public void stop(){
                super.stop();
                if (mp !=null){
                mp.release();
                mp = null;
                }
                };
    
  • @akenaton I copied and pasted the above code. and there is a red line at line 23. the error is

    the function getAssets() does not exist.

  • it exists!!!!

  • edited October 2015

    @akenaton It doesn't exist on my PC. Do I need to add a library or something like that?

    alt text

  • @rhythmiccycle tested processing 2 i ll test with 3 perhaps you have to add import AssetManager class

  • edited October 2015

    @rhythmiccycle= right, with processing 3 you have to add context!!!! so:: add this to your import::

        import android.content.Context;
        Context context;
    

    then in the code, line with error change to::

    AssetFileDescriptor afd = context.getAssets().openFd("your.mp3");//which is in the data folder

  • @rhytmiccycle:: no more error in the code but the app crashes when launching on my phone (lollipop); yet i don't think that this is a problem with my phone, nor with the code but with processing:: i have tried to launch the very simple examples (accelerometer && compass) and seen that: -- without changing the code compiler fires error (android tools) at the very beginning when objects are initialized with " this." So i added Context instead of this (as in the code i posted) and now it compiles but the app crashes on the phone with the same kind of errors (attempt to invoke virtual method...); even a very simple thing like :: context = context.getApplicationContext() fires this kind of error... And using processing 2 everything is ok....

  • edited October 2015 Answer ✓

    @rhytmiccycle:: finally i have found the solution; it was not so easy with P3 but it seems to run (on my phone). Explanation of the solution is here :: forum.processing.org/two/discussion/12913/problems-with-android-examples-in-processing-3#latest

    here the new code for P3; try && tell me

             import java.io.File;
                    import java.io.IOException;
                    import android.media.MediaPlayer;
                    import android.media.MediaPlayer.OnPreparedListener;
                    import android.content.res.AssetFileDescriptor;
                    import  android.content.res.Resources;
                   import android.content.res.AssetManager;
                     import android.content.Context;
            import android.app.Activity;
            import android.os.Bundle;
            import android.app.Application;
    
            /////////////////////////////////////////////////////////
    
            MediaPlayer mp;
            public boolean loop = true;
            AssetManager am;
         Context context; 
         boolean premiere = false;
    
         Activity act;
         AssetFileDescriptor afd;
         boolean AppliAndroid = false;
    
    
         public   void setup(){
              orientation(PORTRAIT);
              background(255,0,0);
              fill(255);
              textSize(24);
              text("SONG IS PLAYING", 200,300);
              act = this.getActivity();
           context = act.getApplicationContext();
          // testClass();
    
    
    
    
           try {
              mp = new MediaPlayer();
    
            afd = context.getAssets().openFd("altastrada.mp3");//which is in the data folder
          mp.setDataSource(afd.getFileDescriptor());
          mp.prepare();
          } catch(IOException e) {
            println("j'arrive pas à préparer");
            }
             mp.setLooping(loop);
              mp.start();
    
    
           };
    
        public    void draw(){
    
            };
    
            protected void testClass() {
    
        Class<?> WhatClass = this.getClass();
        while (WhatClass!= null) {
          println("Classe=========" + WhatClass);
          WhatClass = WhatClass.getSuperclass();
          if (WhatClass != null) {
            if (WhatClass.toString().toLowerCase().indexOf("android.app.") > -1) {
              println("What SuperClass===" + WhatClass);
              AppliAndroid = true;
              break;
            }else{
              println("Class=======instanceof" + WhatClass);
            }
          }
        }
            }
    
    
     public void pause(){
    super.pause();
    if (mp !=null){
    mp.release();
    mp = null;
    }
    };
    
            public void stop(){
            super.stop();
            if (mp !=null){
            mp.release();
            mp = null;
            }
            };
    
  • That last code WORKS!!!!!!!!!!!!

  • edited October 2015

    I'm trying to get it to play with as little lines as possible. The code below also plays!

    Thank you akenaton!!

    
    import android.media.MediaPlayer;
    import android.content.res.AssetFileDescriptor;
    import android.content.Context;
    import android.app.Activity;
    
    /////////////////////////////////////////////////////////
    
    MediaPlayer mp;
    Context context; 
    Activity act;
    AssetFileDescriptor afd;
    
    void setup() {
      act = this.getActivity();
      context = act.getApplicationContext();
      try {
        mp = new MediaPlayer();
        afd = context.getAssets().openFd("test.mp3");//which is in the data folder
        mp.setDataSource(afd.getFileDescriptor());
        mp.prepare();
      } 
      catch(IOException e) {
        println("file did not load");
      }
      mp.start();
    };
    
    void draw() {
    };
    
    

    Next I want a program that has 2 mp3's and plays one depending on an event.

    I'll most likely start a new thread in a few days.

  • @akenton what is the point of the "testClass"??

  • Answer ✓

    @rythmiccycle: happy to see that it works; another one (examples which does nor run with p3, see the post) tells me that it does not work and i cannot see why. As for testClass() you can call it, i have forgotten it in thecode but it s absolutely useless for playing sound, only it s one of the class i have coded for better understanding about how android mode runs in processing...Call it && you ll see...And dont forget to put answered (if you have not done till now) for others (they are a lot) having this kind of problems with p3.

  • Hello, I tried both of your Codes but both of them aren’t working for me, the App launches but there’s no sound playing. The line " act = this.getActivity();" is highlighted and its said that the Function "getActivity()" does not exist. Anyone knows where this comes from? Thank you very much !

  • @mago==== dont bother about "this.getActivity" your problem is another one::: filedescriptor or.... put the err console

  • Thank you for you quick support akenaton! I finally I found out what caused my Error. I tried out some different Audio formats (.wav, .ogg ) and finally I was able to play my Files using mp3 format.

  • @akenaton Thank you for your hard work on this problem. I am porting a game to Android and I ran into issues with apwidgets as well in Processing 3.0.1 - specifically, the apwidgets library code that accesses the assets seems to be broken/outdated. I used MediaPlayer for the music and SoundPool for the sound effects and implemented based on the following resources:

    https://dzone.com/articles/playing-sounds-android http://www.tutorialspoint.com/android/android_mediaplayer.htm http://examples.javacodegeeks.com/android/android-soundpool-example/

    and my working code is here: https://github.com/chris0/FloodGate/blob/Android/floodit/floodit.pde

    Hopefully, those links will be helpful to others trying to add music and sounds into their Android sketches.

  • Thanks to contributors above... I've spent 2 days re-installing Android SDKs, reading forums, googling and messing about with mediaPlayer and soundPool. @chrisgoc thanks a lot for the code... I've distilled a simple example from that using soundPool which works for me.

    I'm using OSX 10.10.5, processing 3.0.1, compiled against ADK 5.0.1 (21) and running on a Motorola Moto G XT1068 phone, running Android 5.0.2.

    the example files 51.mp3 and 52.mp3 (in my case) are in the sketch's data folder.

    // Basic test of sound on android using soundPool for short FX
    // based on code by @chrisgoc 
    // See https://forum.processing.org/two/discussion/comment/53262
    // and https://github.com/chris0/FloodGate/blob/Android/floodit/floodit.pde
    
    
    import android.app.Activity;
    import android.content.res.AssetFileDescriptor;
    import android.content.Context;
    import android.media.MediaPlayer;
    import android.media.SoundPool;
    import android.media.AudioManager;
    
    /////////////////////////////////////////////////////////
    
    SoundPool soundPool;
    HashMap<Object, Object> soundPoolMap;
    Activity act;
    Context cont;
    AssetFileDescriptor afd1, afd2;
    int s1, s2;
    int streamId;
    
    
    void playSound(int soundID)
    {
      // play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
    
      soundPool.stop(streamId); // kill previous sound - quick hack to void mousePressed triggering twice
      streamId = soundPool.play(soundID, 1.0, 1.0, 1, 0, 1f);
    }
    
    void setup() {
      act = this.getActivity();
      cont = act.getApplicationContext();
    
      // load up the files
      try {
        afd1 = cont.getAssets().openFd("51.mp3");
        afd2 = cont.getAssets().openFd("52.mp3");
      } 
      catch(IOException e) {
        println("error loading files:" + e);
      }
    
      // create the soundPool HashMap - apparently this constructor is now depracated?
      soundPool = new SoundPool(12, AudioManager.STREAM_MUSIC, 0);
      soundPoolMap = new HashMap<Object, Object>(2);
      soundPoolMap.put(s1, soundPool.load(afd1, 1));
      soundPoolMap.put(s2, soundPool.load(afd2, 1));
    };
    
    void draw() {
    
      fill(#B4BDE8);
      rect(0, 0, width, height/2);
      fill(#E8B4E5);
      rect(00, (height/2), width, height/2);
    
    
      if (mousePressed) {
    
        if (mouseY < height/2) {
          playSound(1);
        } else {
          playSound(2);
        }
    
      }
    };
    
  • GpmGpm
    edited January 2016

    ~O)

  • `import android.media.MediaPlayer; import android.content.res.AssetFileDescriptor; import android.content.Context; import android.app.Activity;

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

    MediaPlayer mp; Context context; Activity act; AssetFileDescriptor afd;

    void setup() { act = this.getActivity(); context = act.getApplicationContext(); try { mp = new MediaPlayer(); afd = context.getAssets().openFd("test.mp3");//which is in the data folder mp.setDataSource(afd.getFileDescriptor()); mp.prepare(); } catch(IOException e) { println("file did not load"); } mp.start(); };

    void draw() { };`

    Screen Shot 2016-04-25 at 5.00.23 PM

    I implemented the above code separately, it worked although act = this.getActivity() code has a underlined error, I get this error as attached for the act = this.getActivity(); when integrated it together with my android mode application is there any help that I can get? Any other suggestion of using mp3 file to play.

  • Did you try the cassette library? After you install it, run their examples. It works for me in Processing 3.0.1 and Android 5.0.1.

    Notice in the examples you can run a file using a cpl of lines. I hope this helps,

    Kf

  • Thank you Kf, you were right the cassette library worked well and tried after reading your suggestion.

  • @rhythmiccycle Hello, did you try the code with two or more .mp3 files? i can not do it, i have error with my code, do you can help me? Thanks :)

  • @eliazherrera Can you post your code? Did you try the cassette library? I would suggest running the examples that come with the library.

    Kf

  • @eliazherrera I wrote this about a year ago. I did eventually get multiple mp3's to play, but only with short length files (like under 5 seconds). I would have to find my old files, and I'm too busy today. I might be able to help you tomorrow. If you still need help tomorrow, post here and then I'll find my old files and post the code.

  • edited October 2016

    Hello @kfrajer I saw cassette library,it's run on mi android device, it does not has pause function really? i would like play a file when press a key and when released the key pause the file. try that with multiple keys and files. i have tried modify @rhythmiccycle code:

    import android.media.MediaPlayer;
    import android.content.res.AssetFileDescriptor;
    import android.content.Context;
    import android.app.Activity;
    
    /////////////////////////////////////////////////////////
    
    MediaPlayer mp1;
    MediaPlayer mp2;
    Context context1;
    Context context2;
    Activity act1;
    Activity act2;
    AssetFileDescriptor afd1;
    AssetFileDescriptor afd2;
    
    void setup() {
      act1 = this.getActivity();
      context1 = act1.getApplicationContext();
      act2 = this.getActivity();
      context2 = act2.getApplicationContext();
      try {
        mp1 = new MediaPlayer();
        mp2 = new MediaPlayer();
        afd1 = context1.getAssets().openFd("sound1.mp3");//which is in the data folder
        afd2 = context2.getAssets().openFd("sound2.mp3");
        mp1.setDataSource(afd1.getFileDescriptor());
        mp2.setDataSource(afd2.getFileDescriptor());
        mp1.prepare();
        mp2.prepare();
      } 
      catch(IOException e) {
        println("file did not load");
      }
    //  mp.start();
    };
    
    void draw() {
    };
    void keyPressed(){
    if(key == 'b'){
      mp1.start();
      }
    if(key == 'r'){
      mp2.start();
      }
    }
    void keyReleased(){
    if (key=='b'){
      mp1.pause();
      }
    if (key=='r'){
      mp2.pause();
      }
    }
    
  • Thanks @rhythmiccycle I will wait your help tomorrow! :)

Sign In or Register to comment.