无线电流媒体

时间:2014-04-11 13:43:58

标签: android streaming radio

我设置了一个无线电层,但最大的问题是,当手机屏幕变黑时,收音机会停止流式传输。有谁知道为什么这一切?

以下是代码:

public class MainActivity extends Activity implements OnClickListener {

private Button buttonPlay;

private Button buttonStopPlay;

private MediaPlayer player;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initializeUIElements();

    initializeMediaPlayer();
}

private void initializeUIElements() {



    buttonPlay = (Button) findViewById(R.id.buttonPlay);
    buttonPlay.setOnClickListener(this);

    buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
    buttonStopPlay.setEnabled(false);
    buttonStopPlay.setOnClickListener(this);

}

public void onClick(View v) {
    if (v == buttonPlay) {
        startPlaying();
    } else if (v == buttonStopPlay) {
        stopPlaying();
    }
}

private void startPlaying() {
    buttonStopPlay.setEnabled(true);
    buttonPlay.setEnabled(false);


    player.prepareAsync();

    player.setOnPreparedListener(new OnPreparedListener() {

        public void onPrepared(MediaPlayer mp) {
            player.start();
        }
    });

}

private void stopPlaying() {
    if (player.isPlaying()) {
        player.stop();
        player.release();
        initializeMediaPlayer();
    }

    buttonPlay.setEnabled(true);
    buttonStopPlay.setEnabled(false);

}

private void initializeMediaPlayer() {
    player = new MediaPlayer();
    try {        
         player.setDataSource("http://69.46.75.99/");
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

        public void onBufferingUpdate(MediaPlayer mp, int percent) {

            Log.i("Buffering", "" + percent);
        }
    });
}

@Override
protected void onPause() {
    super.onPause();
    if (player.isPlaying()) {
        player.stop();
    }
}

}

1 个答案:

答案 0 :(得分:1)

您应该考虑使用Service,否则您需要获得部分唤醒锁。使用Service比较棘手但是更好的选择。

请参阅Using a Service with MediaPlayer