2

If I have this method in a jar library:

public void playAudioFile()
{
  ClassLoader cLoader = getClass().getClassLoader();
  URL url = cLoader.getResource("audio.mp3"); // in the resource of the jar library
  System.out.println(url.toString());

  MediaPlayer mediaPlayer = new MediaPlayer();
  mediaPlayer.setDataSource(url);
}

After compiling the library, I have: MySDK.jar

When I add the MySDK.jar into my android application and try to play an audio file:

private void playAudio()
{
   MySDK.Audio audio = new MySDK.Audio();
   audio.playAudioFile();
}

After compiling the android application, I have: mysampleapp.apk

When debugging the application, the audio file can't be played because:

System.out.println(url.toString());

gives:

jar:file:/data/app/com.mysampleapp.apk!/audio.mp3

The path of the audio should be from the jar file not from the sample app. Therefore, the audio file can not be played.

What did I do wrong, and how can I play an audio file as a resource file from the jar library?

halfer
  • 19,824
  • 17
  • 99
  • 186
olidev
  • 20,058
  • 51
  • 133
  • 197

5 Answers5

1

I don't think it's possible to start playback of an mp3 file using a method from within a .jar in Android. If you need to keep the .jar and play the mp3 that lies within it, I'd temporarily unzip the mp3 to the SD card and play it from there.

Dennis Winter
  • 2,027
  • 4
  • 32
  • 45
0

I see only two solutions:

  • The jar file must contains the mp3.
  • Add the base url as parameters.
julien dumortier
  • 1,303
  • 1
  • 13
  • 28
  • I prefer that the jar contains the mp3 but if I enclose the jar inside an application, I got the problem: jar:file:/data/app/com.mysampleapp.apk!/audio.mp3 – olidev Feb 25 '13 at 22:38
0

Dalvik doesn't know about your library, it only knows your app. One way I think you could work around this is by passing an app-specific resource as a parameter to the playAudioFile() method (or, perhaps, you could initialize a property of its class). That way you could copy the file to a proper directory that belongs to your app and still have reusability for your class.

DigCamara
  • 5,540
  • 4
  • 36
  • 47
0

Hi try these code in your playAudioFile() method

    URL defaultSound = getClass().getResource("/folder/folder/audio.wav");
    File soundFile = new File(defaultSound.toURI());
    System.out.println("defaultSound " + defaultSound);  // check the URL!
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(defaultSound);
    Clip clip = AudioSystem.getClip();
    clip.open(audioInputStream);
    clip.start( );
androidgeek
  • 3,440
  • 1
  • 15
  • 27
0

I suspect that this question is very similar to another one on SO (but I don't know how to flag that). The answer I provided to that one is at: Convert a string to a resource Uri for mp3 playback

In essence you need to get the URI correct, as the above link explains.

Community
  • 1
  • 1
Neil Townsend
  • 6,024
  • 5
  • 35
  • 52