繁体   English   中英

流音频在Android中不起作用

[英]Streaming audio not working in Android

我敢肯定这个问题已经被问过了,但是我一直找不到可靠的答案。 我正在尝试从服务器加载流音频。 它是音频/ AAC文件

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

我正在使用的代码是

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

这是正确的实现吗? 我不确定我要去哪里。 有人可以帮我吗。

方法prepareAsync()是异步的-引用文档:

准备播放器异步播放。

您需要调用setOnPreparedListener() ,提供一个MediaPlayer.OnPreparedListener 然后,在该侦听器的onPrepared() ,可以调用start()

不支持AAC流格式,并且您不能直接播放Android版本低于2.2的Shoutcast流。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM