Unable to load sound in Android

Hey all!

I have gone through every topic on the subject and tried every example, but I always get the exception message and sound fails to load. I have tried the go-to example:

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("MYSOUND.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() {
};

As well as the more complex examples:

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("MYSOUND.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(){

        };

Sound just refuses to load. I get the exception message every time.

Answers

  • I was able to play sounds by downloading the cassette library.

    import cassette.audiofiles.SoundFile;
    
    SoundFile music;
    
    void settings() {
      fullScreen();
      //size(1000, 1000);
    }
    
    void setup() { 
        background(255, 0, 0);
    
        music = new SoundFile(this, "MYSOUND.mp3");
        music.loop();
    }
    
    void draw() {
    }
    

    However, I still want to know: is this a data-efficient way to play short sound effects? Is this a data-efficient way to play music?

    Thanks in advance for the answers.

  • edited October 8

    @randomdude===

    your sound is in the data folder, right??? and you ask for assets, right?? so..... put your sound in assets folder!

  • @akenaton

    I created a folder called 'assets' and I put my sound there. It still doesn't work.

    Can't I just use cassettes? The code there is so simple. Would they work for short sound effects, too, or do I absolutely need SoundPool for these?

  • edited October 8

    @randomdude===

    tired out; the code you are using is mine and i 'm absolutely sure that it runs! cassette is useless. i ll give a look ASAP

  • edited October 8

    I have tried using both codes in my OP, and have tried having my sound file both in DATA and ASSETS folder, and it still doesn't load.

    Console after running first code:

    Build folder: C:\Users\User\AppData\Local\Temp\android5344686476971354542sketch NDK is missing a "platforms" directory. If you are using NDK, verify the ndk.dir is set to a valid NDK directory. It is currently set to C:\Users\User\Documents\Processing\android\sdk\ndk-bundle. If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

    The setTestClassesDir(File) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the setTestClassesDirs(FileCollection) method instead. The getTestClassesDir() method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the getTestClassesDirs() method instead. The ConfigurableReport.setDestination(Object) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the method ConfigurableReport.setDestination(File) instead. :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE :app:prepareComAndroidSupportAnimatedVectorDrawable2520Library :app:prepareComAndroidSupportAppcompatV72520Library :app:prepareComAndroidSupportDesign2520Library :app:prepareComAndroidSupportPercent2301Library :app:prepareComAndroidSupportRecyclerviewV72520Library :app:prepareComAndroidSupportSupportCompat2520Library :app:prepareComAndroidSupportSupportCoreUi2520Library :app:prepareComAndroidSupportSupportCoreUtils2520Library :app:prepareComAndroidSupportSupportFragment2520Library :app:prepareComAndroidSupportSupportMediaCompat2520Library :app:prepareComAndroidSupportSupportV42520Library :app:prepareComAndroidSupportSupportVectorDrawable2520Library :app:prepareComAndroidSupportTransition2520Library :app:prepareComGoogleAndroidSupportWearable200Library :app:prepareDebugDependencies :app:compileDebugAidl :app:compileDebugRenderscript :app:generateDebugBuildConfig :app:generateDebugResValues :app:generateDebugResources :app:mergeDebugResources :app:processDebugManifest :app:processDebugResources :app:generateDebugSources :app:incrementalDebugJavaCompilationSafeguard :app:javaPreCompileDebug :app:compileDebugJavaWithJavac :app:compileDebugNdk NO-SOURCE :app:compileDebugSources :app:mergeDebugShaders :app:compileDebugShaders :app:generateDebugAssets :app:mergeDebugAssets :app:transformClassesWithDexForDebug :app:mergeDebugJniLibFolders :app:transformNativeLibsWithMergeJniLibsForDebug :app:processDebugJavaRes NO-SOURCE :app:transformResourcesWithMergeJavaResForDebug :app:validateSigningDebug :app:packageDebug :app:assembleDebug

    BUILD SUCCESSFUL in 6s 35 actionable tasks: 35 executed file did not load

    Console after running second code:

    Build folder: C:\Users\User\AppData\Local\Temp\android4933602869803909844sketch NDK is missing a "platforms" directory. If you are using NDK, verify the ndk.dir is set to a valid NDK directory. It is currently set to C:\Users\User\Documents\Processing\android\sdk\ndk-bundle. If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

    The setTestClassesDir(File) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the setTestClassesDirs(FileCollection) method instead. The getTestClassesDir() method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the getTestClassesDirs() method instead. The ConfigurableReport.setDestination(Object) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the method ConfigurableReport.setDestination(File) instead. :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE :app:prepareComAndroidSupportAnimatedVectorDrawable2520Library :app:prepareComAndroidSupportAppcompatV72520Library :app:prepareComAndroidSupportDesign2520Library :app:prepareComAndroidSupportPercent2301Library :app:prepareComAndroidSupportRecyclerviewV72520Library :app:prepareComAndroidSupportSupportCompat2520Library :app:prepareComAndroidSupportSupportCoreUi2520Library :app:prepareComAndroidSupportSupportCoreUtils2520Library :app:prepareComAndroidSupportSupportFragment2520Library :app:prepareComAndroidSupportSupportMediaCompat2520Library :app:prepareComAndroidSupportSupportV42520Library :app:prepareComAndroidSupportSupportVectorDrawable2520Library :app:prepareComAndroidSupportTransition2520Library :app:prepareComGoogleAndroidSupportWearable200Library :app:prepareDebugDependencies :app:compileDebugAidl :app:compileDebugRenderscript :app:generateDebugBuildConfig :app:generateDebugResValues :app:generateDebugResources :app:mergeDebugResources :app:processDebugManifest :app:processDebugResources :app:generateDebugSources :app:incrementalDebugJavaCompilationSafeguard :app:javaPreCompileDebug :app:compileDebugJavaWithJavac :app:compileDebugNdk NO-SOURCE :app:compileDebugSources :app:mergeDebugShaders :app:compileDebugShaders :app:generateDebugAssets :app:mergeDebugAssets :app:transformClassesWithDexForDebug :app:mergeDebugJniLibFolders :app:transformNativeLibsWithMergeJniLibsForDebug :app:processDebugJavaRes NO-SOURCE :app:transformResourcesWithMergeJavaResForDebug :app:validateSigningDebug :app:packageDebug :app:assembleDebug

    BUILD SUCCESSFUL in 6s 35 actionable tasks: 35 executed j'arrive pas Г  prГ©parer

    Why is cassettes useless?

  • Cassette should work and it has limited features, but it is good for building small programs. However, when it comes to managing the app's life cycle, it seems the library needs some changes. MediaPlayer should work in your case although i am not able to assist any further atm.

    Kf

  • @randomdude===

    the error message is mainly about ndk that this code does not use, it is probably a bug, yet without consequence in your case (if you really want to get rid of it you can install the ndk platform yourself but why???) - the real error is a JIO exception which seems to mean that the file is found but cannot be loaded by mediaplayer; to be sure or trying to be, you can add a setOnPreparedListener() to your player and start the sound when the callback is received; perhaps also you can try to create a runnable or use prepareAsync() instead of prepare. It is difficult to answer more without being sure that your sound is a good one (and knowing is weight && length): in some cases .mp3 do not work. Try with another one...

    As for sound effects (sounds <5") eg. for a game Android has the soundPool class. As for more complex things about sound you can also use AudioTrackManager.With these 3 solutions already present Cassette lib is useless.

  • edited October 9

    https://vocaroo.com/i/s0uqend8cmxz

    This is the sound I'm using. It's a short mp3 sound recorded via Windows recorder.

    I did use an online converter to conver it from wav to mp3. Could that have something to do with the issue?

    EDIT: I tried (almost) all of the solutions mentioned above and nothing worked...... I also tried it with various different files from various different sources.

    I just didn't try setOnPreparedListener(). I'm not sure what arguments to put in it.

  • edited October 9

    I think it has something to do with this error I get in the console (you can find it above):

    The setTestClassesDir(File) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the setTestClassesDirs(FileCollection) method instead. The getTestClassesDir() method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the getTestClassesDirs() method instead. The ConfigurableReport.setDestination(Object) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the method ConfigurableReport.setDestination(File) instead.

    Can someone clarify on what it means?

    EDIT: I can't figure it out... I don't see any other option than to use cassettes. Nobody actually answered: apart from the issues with the app's lifecycle (what are they anyway?), is there any other reason I shouldn't use cassettes to both play music AND short 1-2 second sound effects in my app. Would it make the code too heavy?

  • The cassette should work. I remember there was some issues when the app was being sent to the background (back button) then one was not able to free the resources properly. At that time, the OP solved his issues by moving to MediaPlayer as advised by akenaton. If cassette work for your project, you should go ahead an use it. If you get into any trouble, you could continue pursuing any of the alternatives above.

    Please keep in mind that when I tested the cassette lib b4, I was using an older Android Mode, not the latest 4.0

    Kf

  • @kfrajer

    I have been experimented with cassettes for some time and can conclude that they are indeed, as akenaton said, useless. Extremely buggy and unreliable, stop at random points, etc.

    If someone has any input on my problem it is very, very welcome. :(

  • edited October 10

    If this is of any help, I tried it this way:

    import android.media.MediaPlayer;
    import android.content.res.AssetFileDescriptor;
    import android.content.Context;
    import android.app.Activity;
    
    /////////////////////////////////////////////////////////
    
    MediaPlayer mp = new MediaPlayer();
    Context context; 
    AssetFileDescriptor afd;
    
    void setup() {
      try {
      afd = context.getAssets().openFd("MYSOUND.mp3");
      mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
      mp.prepare();
      mp.start();
    
      } 
      catch(IllegalArgumentException e) {
        e.printStackTrace();
      }
      catch(IllegalStateException e) {
        e.printStackTrace();
      }
      catch(IOException e) {
        e.printStackTrace();
       }
    };
    
    void draw() {
    };
    

    And got this in console:

    BUILD SUCCESSFUL in 7s 35 actionable tasks: 35 executed FATAL EXCEPTION: Animation Thread Process: processing.test.sketch_171009c, PID: 15932 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference at processing.test.sketch_171009c.sketch_171009c.setup(sketch_171009c.java:37) at processing.core.PApplet.handleDraw(Unknown Source) at processing.core.PSurfaceNone.callDraw(Unknown Source) at processing.core.PSurfaceNone$AnimationThread.run(Unknown Source)

  • @randomdude===

    • nothing strange: context is undefined

    • what is strange is why you dont get the other error messages(ndk)

  • edited October 10

    @akenaton

    Then I am completely at a loss... I tried so many things with the MediaPlayer.

    Hmmm, I'm not sure if I'm getting SoundPool right. Whenever possible, can you give a short code snippet only showing how to use SoundPool? I don't think there's one anywhere in the forum.

    Edit: I HAVE SUCCESSFULLY PLAYED SOUND WITH SOUNDPOOL. However, I do not fully understand my code (I just tried a lot of different things and one just so happened to work.) I will post it when I can.

    However, I still can’t play music. MediaPlayer still refuses to work.

  • @randomdude===

    media player && the code i have given works. i cannot download your sound from your link: they ask me to pay....put it elsewhere.

  • edited October 10

    The problem is not with the sound file. I tried it with many files from different sources.

    This is the code that worked for me with SoundPool (Do you think it's reliable?):

    import android.media.AudioManager;
    import android.media.SoundPool;
    import android.content.res.AssetFileDescriptor;
    import android.content.res.AssetManager;
    import android.content.Context;
    import android.app.Activity;
    SoundPool SP;
    Context context;
    AssetFileDescriptor descriptor;
    Activity act;
    AssetManager am;
    int sound1, sound2;
    
    void setup() {
      fullScreen();
      SP = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
      try {
        am = getAssets();
        sound1 = SP.load(this.getActivity().getApplicationContext().getAssets().openFd("MYSOUND2.mp3"), 1);
        sound2 = SP.load(this.getActivity().getApplicationContext().getAssets().openFd("MYSOUND1.mp3"), 1);
      } 
      catch (IOException e) {
      }
    }
    AssetManager getAssets() {
      return null;
    }
    void draw() {
    }
    void mousePressed() {
      if (mouseY<height/2) {
        SP.play(sound1, 0.9f, 0.9f, 2, 0, 1.0);
      } else if (mouseY>=height/2) {
        SP.play(sound2, 0.9f, 0.9f, 2, 0, 1.0);
      }
    }
    

    I also tried the MediaPlayer code in a similarly simplified version:

    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() {
      context = this.getActivity().getApplicationContext();
      try {
        mp = new MediaPlayer();
        mp.setDataSource(context.getAssets().openFd("MYSOUND.mp3").getFileDescriptor());
        mp.prepare();
      } 
      catch(IOException e) {
        println("file did not load");
      }
      mp.start();
    };
    
    void draw() {
    };
    

    But file still does not load (naturally, because that's practically the same code..) and then I tried this:

    MediaPlayer mp;
    Context context; 
    Activity act;
    AssetFileDescriptor afd;
    AssetManager am;
    
    void setup() {
      context = this.getActivity().getApplicationContext();
      try {
        mp = new MediaPlayer();
        am = getAssets();
        mp.setDataSource(context.getAssets().openFd("ALL THE RAGE BACK HOME.mp3").getFileDescriptor());
        mp.prepare();
      } 
      catch(IOException e) {
        println("file did not load");
      }
      mp.start();
    }
    AssetManager getAssets() {
      return null;
    }
    
    void draw() {
    };
    

    And it - also - did not work.

Sign In or Register to comment.