Tashen Jazbi Tashen Jazbi - 6 months ago 17
Java Question

Audio file from URL with space in it not playing in my application

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();
}

Answer

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