2

I am developing an application which plays audio files from my server where I've uploaded them. The problem is that only those files play which don't have a space in their file name and files having a space in the file file are not being played. For example, I've two words.

word1=cricket
word2=play cricket
http://mydomain.com/games/cricket.mp3 is playing sound
http://mydomain.com/games/play cricket.mp3 is not playing

Every word which have space in it is not being played. What's wrong in my code?

MediaPlayer mp = new MediaPlayer();

try {
    mp.setDataSource(url);
    mp.prepare();
    mp.start();
} 
catch (Exception e) {
    e.printStackTrace();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tashen Jazbi
  • 1,068
  • 1
  • 16
  • 41

1 Answers1

4

Using URLEncoder is a good option, however can be a little unwieldy (you'll need to escape only the end part).

If you are reasonably confident that it's just the spaces causing problems another option is just to replace them like so:

String url = "http://example.com/games/play cricket.mp3"; 
String fixedUrl = url.replaceAll("\\s", "%20");

MediaPlayer mp = new MediaPlayer();

try {
    mp.setDataSource(fixedUrl);
    mp.prepare();
    mp.start();
} catch (Exception e) {
    e.printStackTrace();
}  

You can read more about percent encoding here: http://en.wikipedia.org/wiki/Percent-encoding

Ken Wolf
  • 23,133
  • 6
  • 63
  • 84