12

我的活动代码如下:

public class Player extends Activity implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnBufferingUpdateListener, MusicFocusable {

    private Boolean playState = false;  
    private String station = "http://38.101.19.5:9157";
    public static final float DUCK_VOLUME = 0.1f;
    private String artistName = null;
    private String trackName = null;

    private TextView artist;
    private TextView track;
    private TextView status;
    private Button play;

    enum AudioFocus {
        NoFocusNoDuck, // we don't have audio focus, and can't duck
        NoFocusCanDuck, // we don't have focus, but can play at a low volume
                        // ("ducking")
        Focused // we have full audio focus
    }

    private AudioFocus mAudioFocus = AudioFocus.NoFocusNoDuck;

    private MediaPlayer mPlayer = null;
    private AndroidShoutcastLib shoutcast;
    private AudioManager mAudioManager;
    AudioFocusHelper mAudioFocusHelper = null;

    Handler handler = new Handler();

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

        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

        // create the Audio Focus Helper, if the Audio Focus feature is
        // available (SDK 8 or above)
        if (android.os.Build.VERSION.SDK_INT >= 8) {
            mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(),
                    this);
        }
        else {
            mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus
        }

        status = (TextView) findViewById(R.id.status);

        artist = (TextView) findViewById(R.id.artist);
        artist.setSelected(true);

        track = (TextView) findViewById(R.id.track);
        track.setSelected(true);

        play = (Button) findViewById(R.id.play);

        play.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View btn) {
                if (!playState) {
                    play.setText("Pause");
                    handler.postDelayed(handlePlayRequest, 300);
                }
                else {
                    play.setText("Play");
                    status.setText("Press Play");
                    handler.postDelayed(handlePlayRequest, 300);
                }
            }

        });

        shoutcast = new AndroidShoutcastLib();

        try {
            shoutcast.setShoutcastUrl(station);
        } catch (InvalidStreamURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        shoutcast.setOnMetadataChangedListener(new MetadataListener(){

            @Override
            public void OnMetadataChanged(Metadata item) {
                artistName = item.artist;
                trackName = item.track;             
                updateMeta();
            }
        });

        setVolumeControlStream(AudioManager.STREAM_MUSIC);      
    }

    public void onDestroy() {
        super.onDestroy();

        shoutcast = null;
        handler.removeCallbacks(handlePlayRequest);
    }

    public void updateMeta() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                // This gets executed on the UI thread so it can safely modify Views
                artist.setText(artistName);
                track.setText(trackName);
            }
        });
    }

    private final Runnable handlePlayRequest = new Runnable() {
        public void run() {
            if (playState) {
                Log.d("Player", "Stop Called");
                giveUpAudioFocus();
                mPlayer.stop();
                mPlayer.reset();
                mPlayer.release();
                shoutcast.stopStream();
                mPlayer = null;
                playState = false;
            }
            else {
                Log.d("Player", "Play Called");
                createMediaPlayer();
                getAudioFocus();

                try {
                    mPlayer.setDataSource(shoutcast.startStream());
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvalidStreamURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mPlayer.prepareAsync();
            }
        }
    };

    private void createMediaPlayer() {
        mPlayer = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do
        // that, the CPU might go to sleep while the song is playing,
        // causing playback to stop.
        //
        // Remember that to use this, we have to declare the
        // android.permission.WAKE_LOCK
        // permission in AndroidManifest.xml.
        mPlayer.setWakeMode(getApplicationContext(),
                PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done
        // playing:
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    }

    private void startPlayer() {
        mPlayer.setVolume(1.0f, 1.0f);
        if (!mPlayer.isPlaying()) {
            Log.d("Player", "Starting Playback");
            mPlayer.start();
            playState = true;
            status.setText("Streaming");
        }               
    }

    private void getAudioFocus() {
        if (mAudioFocus != AudioFocus.Focused && mAudioFocusHelper != null
                && mAudioFocusHelper.requestFocus())
            mAudioFocus = AudioFocus.Focused;
    }

    private void giveUpAudioFocus() {
        if (mAudioFocus == AudioFocus.Focused && mAudioFocusHelper != null
                && mAudioFocusHelper.abandonFocus())
            mAudioFocus = AudioFocus.NoFocusNoDuck;
    }

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

    @Override
    public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        playState = false;
        handler.post(handlePlayRequest);
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer arg0) {
        startPlayer();      
    }

    @Override
    public void onCompletion(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onGainedAudioFocus() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLostAudioFocus(boolean canDuck) {
        // TODO Auto-generated method stub

    }

}

我的要求是将此活动转换为服务类,我尝试过但没有得到,因为我是 Android 新手,也是编程新手,

有人可以帮忙吗?

4

3 回答 3

7

如果您只需要在您的应用程序中播放音乐,请在从您的应用程序启动的线程中播放它/使用AsyncTask类为您完成。

使用此代码。添加此类(包含在您的活动类中)。

public class BackgroundSound extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr); 
        player.setLooping(true); // Set looping 
        player.setVolume(100,100); 
        player.start(); 

        return null;
    }

}

另一方面,如果您想使用服务,可以查看此页面

于 2013-05-02T11:39:26.787 回答
4

首先,确保你理解为什么要使用 Service 而不是AsyncTask。真的很有帮助,并说明了为什么应该使用 Service 而不是 AsyncTask 在后台播放音乐。

对您来说非常方便。它清楚地展示了如何使用服务在后台播放音乐。

于 2015-03-09T06:52:12.057 回答
3

要遵循的几个步骤......

1.首先浏览服务示例。

2.从此活动启动服务,即,每当此应用打开导航活动以服务活动---->服务时。

3.在服务中覆盖onstart()。

4.在 onstart() 中创建音乐播放器函数并调用你想要的歌曲。

5.然后像这样开始 mp.play();

6.现在它将在后台运行

于 2013-05-02T11:41:33.360 回答