无法播放来自URL(广播)的流

时间:2013-12-02 11:17:13

标签: android media-player

我想通过我的Android手机播放广播电台播放的音乐。

package com.greenbits.kissfmcyprus;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity implements OnPreparedListener
{
    private final String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MediaPlayer mediaPlayer = new MediaPlayer();
        try
        {
            mediaPlayer.setDataSource("http://live.istoikona.com/kiss");
        }
        catch (IllegalArgumentException e)
        {
            Log.e(TAG, e.getMessage());
        }
        catch (SecurityException e)
        {
            Log.e(TAG, e.getMessage());
        }
        catch (IllegalStateException e)
        {
            Log.e(TAG, e.getMessage());
        }
        catch (IOException e)
        {
            Log.e(TAG, e.getMessage());
        }

        mediaPlayer.setOnPreparedListener(this);

        Log.e(TAG, "ready to call prepare");
        mediaPlayer.prepareAsync();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onPrepared(MediaPlayer mp)
    {
        Log.i(TAG, "prepared successfully");
        mp.start();
    }
}

我还在清单中声明我想使用互联网。 在日志中,我收到代码为-1004的错误,这是文件或网络相关的操作错误。

当我尝试在PC的浏览器中打开相同的URL时,它可以正常播放音乐。 我做错了吗?

1 个答案:

答案 0 :(得分:0)

    String urlAdress ="http://live.istoikona.com/kiss";   
    Uri uri = Uri.parse(urlAdress);
    player = new MediaPlayer();

    Log.d("UYARI", "PLAYER WAS CREATED");

    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setDataSource(getApplicationContext(), uri);

    Log.d("UYARI", "SET DATA SOURCE WAS INITIALIZED");

    player.setOnPreparedListener(new OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
            // TODO Auto-generated method stub
            if (!mp.isPlaying()) {

                mp.start();
                Log.d("UYARI", "AT LAST PLAYER WAS STARTED");


            }

        }
    });
    player.prepareAsync();
    Log.d("UYARI", "PREPAREASYNC WAS DONE ");

**但不要忘记在真实手机或智能手机中测试这些代码。因为有时emulater无法播放一些网址。除此之外,不要忘记清单xml **

中的互联网权限