Streaming audio not working in Android

Posted by user320293 on Stack Overflow See other posts from Stack Overflow or by user320293
Published on 2010-12-26T02:45:33Z Indexed on 2010/12/26 2:54 UTC
Read the original article Hit count: 225

Filed under:
|
|
|

Hi,

I'm sure that this question has been asked before but I've been unable to find a solid answer. I'm trying to load a streaming audio from a server. Its a audio/aac file

http://3363.live.streamtheworld.com:80/CHUMFMAACCMP3

The code that I'm using is

private void playAudio(String str) {
  try {
   final String path = str;

   if (path == null || path.length() == 0) {
    Toast.makeText(RadioPlayer.this, "File URL/path is empty",
      Toast.LENGTH_LONG).show();

   } else {
    // If the path has not changed, just start the media player


    MediaPlayer mp = new MediaPlayer();

    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);


    try{
     mp.setDataSource(getDataSource(path));
     mp.prepareAsync();
     mp.start();
    }catch(IOException e){
     Log.i("ONCREATE IOEXCEPTION", e.getMessage());
    }catch(Exception e){
     Log.i("ONCREATE EXCEPTION", e.getMessage());
    } 


   }
  } catch (Exception e) {
   Log.e("RPLAYER EXCEPTION", "error: " + e.getMessage(), e);

  }
 }

 private String getDataSource(String path) throws IOException {
  if (!URLUtil.isNetworkUrl(path)) {
   return path;
  } else {
   URL url = new URL(path);
   URLConnection cn = url.openConnection();
   cn.connect();
   InputStream stream = cn.getInputStream();
   if (stream == null)
    throw new RuntimeException("stream is null");
   File temp = File.createTempFile("mediaplayertmp", ".dat");
   temp.deleteOnExit();
   String tempPath = temp.getAbsolutePath();
   FileOutputStream out = new FileOutputStream(temp);
   byte buf[] = new byte[128];
   do {
    int numread = stream.read(buf);
    if (numread <= 0)
     break;
    out.write(buf, 0, numread);
   } while (true);
   try {
    stream.close();
   } catch (IOException ex) {
    Log.e("RPLAYER IOEXCEPTION", "error: " + ex.getMessage(), ex);
   }
   return tempPath;
  }
 }

Is this the correct implementation? I'm not sure where I'm going wrong. Can someone please please help me on this.

© Stack Overflow or respective owner

Related posts about android

Related posts about audio