Android的播放音乐的背景 [英] Android playing Music in Background

查看:176
本文介绍了Android的播放音乐的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的活动code象下面这样:

 公共类播放器扩展了活动实施OnCompletionListener,
在preparedListener,OnErrorListener,OnBufferingUpdateListener,MusicFocusable {

    私人布尔playState = FALSE;
    私人字符串站=htt​​p://38.101.19.5:9157;
    公共静态最终浮动DUCK_VOLUME = 0.1F;
    私人字符串artistName = NULL;
    私人字符串TRACKNAME = NULL;

    私人TextView的艺术家;
    私人TextView的轨道;
    私人TextView的状态;
    私人按钮来播放;

    枚举AudioFocus {
        NoFocusNoDuck,//我们没有音频设备,而不能鸭
        NoFocusCanDuck,//我们没有重点,但可以以较低音量播放
                        //(回避)
        重点//我们有完整的音频焦点
    }

    私人AudioFocus mAudioFocus = AudioFocus.NoFocusNoDuck;

    私人MediaPlayer的MPLAYER = NULL;
    私人AndroidShoutcastLib Shoutcast的;
    私人AudioManager mAudioManager;
    AudioFocusHelper mAudioFocusHelper = NULL;

    处理程序处理程序=新的处理程序();

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_player);

        mAudioManager =(AudioManager)getSystemService(AUDIO_SERVICE);

        //创建将音频助手,如果将音频功能是
        //用(SDK 8或以上)
        如果(android.os.Build.VERSION.SDK_INT> = 8){
            mAudioFocusHelper =新AudioFocusHelper(getApplicationContext()
                    本);
        }
        其他 {
            mAudioFocus = AudioFocus.Focused; //没有对焦功能,所以我们总是有音频重点
        }

        状态=(TextView中)findViewById(R.id.status);

        艺术家=(TextView中)findViewById(R.id.artist);
        artist.setSelected(真正的);

        轨道=(TextView中)findViewById(R.id.track);
        track.setSelected(真正的);

        玩=(按钮)findViewById(R.id.play);

        play.setOnClickListener(新OnClickListener(){

            @覆盖
            公共无效的onClick(查看BTN){
                如果(!playState){
                    play.setText(暂停);
                    handler.postDelayed(handlePlayRequest,300);
                }
                其他 {
                    play.setText(播放);
                    status.setText(preSS播放);
                    handler.postDelayed(handlePlayRequest,300);
                }
            }

        });

        Shoutcast一样=新AndroidShoutcastLib();

        尝试 {
            shoutcast.setShoutcastUrl(站);
        }赶上(InvalidStreamURLException E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }

        shoutcast.setOnMetadataChangedListener(新MetadataListener(){

            @覆盖
            公共无效OnMetadataChanged(元数据项){
                artistName = item.artist;
                TRACKNAME = item.track;
                updateMeta();
            }
        });

        setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }

    公共无效的onDestroy(){
        super.onDestroy();

        Shoutcast一样= NULL;
        handler.removeCallbacks(handlePlayRequest);
    }

    公共无效updateMeta(){
        handler.post(新的Runnable(){
            @覆盖
            公共无效的run(){
                //这个被UI线程上执行,因此可以安全地修改意见
                artist.setText(artistName);
                track.setText(TRACKNAME);
            }
        });
    }

    私人最终可运行handlePlayRequest =新的Runnable(){
        公共无效的run(){
            如果(playState){
                Log.d(玩家,停止叫);
                giveUpAudioFocus();
                mPlayer.stop();
                mPlayer.reset();
                mPlayer.release();
                shoutcast.stopStream();
                MPLAYER = NULL;
                playState = FALSE;
            }
            其他 {
                Log.d(玩家,戏称为);
                createMediaPlayer();
                getAudioFocus();

                尝试 {
                    mPlayer.setDataSource(shoutcast.startStream());
                }赶上(抛出:IllegalArgumentException E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }赶上(SecurityException异常E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }赶上(IllegalStateException异常E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }赶上(MalformedURLException异常E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }赶上(IOException异常E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }赶上(InvalidStreamURLException E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }
                。MPLAYER prepareAsync();
            }
        }
    };

    私人无效createMediaPlayer(){
        MPLAYER =新的MediaPlayer();

        //确保媒体播放器将获得一个唤醒锁,而
        //播放。如果我们不这样做
        //是,CPU可能会去,而正在播放的歌曲睡觉,
        //导致播放停止。
        //
        //记住,要利用这一点,我们必须申报
        // android.permission.WAKE_LOCK
        //在AndroidManifest.xml中的权限。
        mPlayer.setWakeMode(getApplicationContext(),
                PowerManager.PARTIAL_WAKE_LOCK);

        //我们希望媒体播放器来通知我们,当它准备preparing,
        //它完成时
        //播放:
        mPlayer.setOn preparedListener(本);
        mPlayer.setOnCompletionListener(本);
        mPlayer.setOnErrorListener(本);
    }

    私人无效startPlayer(){
        mPlayer.setVolume(1.0F,1.0F);
        如果(!mPlayer.isPlaying()){
            Log.d(玩家,开始播放);
            mPlayer.start();
            playState = TRUE;
            status.setText(流);
        }
    }

    私人无效getAudioFocus(){
        如果(mAudioFocus = AudioFocus.Focused和放大器;!&安培;!mAudioFocusHelper = NULL
                &功放;&安培; mAudioFocusHelper.requestFocus())
            mAudioFocus = AudioFocus.Focused;
    }

    私人无效giveUpAudioFocus(){
        如果(mAudioFocus == AudioFocus.Focused和放大器;&安培;!mAudioFocusHelper = NULL
                &功放;&安培; mAudioFocusHelper.abandonFocus())
            mAudioFocus = AudioFocus.NoFocusNoDuck;
    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.activity_player,菜单);
        返回true;
    }

    @覆盖
    公共无效onBufferingUpdate(MediaPlayer的为arg0,INT ARG1){
        // TODO自动生成方法存根

    }

    @覆盖
    公共布尔的onError(MediaPlayer的熔点,诠释了什么,整型附加){
        playState = FALSE;
        handler.post(handlePlayRequest);
        返回false;
    }

    @覆盖
    公共无效于prepared(MediaPlayer的为arg0){
        startPlayer();
    }

    @覆盖
    公共无效onCompletion(MediaPlayer的为arg0){
        // TODO自动生成方法存根

    }

    @覆盖
    公共无效onGainedAudioFocus(){
        // TODO自动生成方法存根

    }

    @覆盖
    公共无效onLostAudioFocus(布尔canDuck){
        // TODO自动生成方法存根

    }

}
 

我的要求是把这个活动到服务类,我都试过,但没有得到,因为我是新来的Andr​​oid以及新来编程,

难道任何一个能帮助?

解决方案

如果你想播放背景音乐为您的应用程序而已,然后发挥它从你的应用程序/使用的AsyncTask类来为你做它启动一个线程。

服务的概念是在后台运行;通过背景,意义,通常是当你的应用程序用户界面是不可见。诚然,它可以用来就像你(如果你还记得停止它),但它只是不正确的,而且它消耗你不应该使用的资源。

如果你想peform任务对你的活动的背景下,使用AsyncTask的。

顺便说一句,ONSTART是pcated德$ P $。当你使用的服务,实现onStartCommand。

更新:

我觉得这$​​ C $ C会为你工作。添加这个类(在您的活动类附后)。

 公共类BackgroundSound扩展的AsyncTask<虚空,虚空,虚空> {
@覆盖
保护无效doInBackground(虚空...... PARAMS){
    的MediaPlayer播放器= MediaPlayer.create(YourActivity.this,R.raw.test_cbr);
    player.setLooping(真正的); //设置循环
    player.setVolume(100,100);
    player.start();
    返回null;
 }
   }
 

现在,为了控制音乐,保存annonymously创造它的你BackgroundSound对象来代替。声明它作为一个字段的活动:

  BackgroundSound mBackgroundSound =新BackgroundSound();
 

在您的活动的onResume方法,启动:

 公共无效onResume(){
super.onResume();
mBackgroundSound.execute(空);
}
 

和您的活动的的onPause方法,阻止它:

 公共无效的onPause(){
super.onPause();
mBackgroundSound.cancel(真正的);
}
 

这会工作。

I have My Activity Code like Below:

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

    }

}

My Requirement is to Convert this Activity to Service Class,I have tried but not getting,Because I'm new to Android as well as new to Programing,

Could any one help?

解决方案

If you want to play background music for your app only, then play it in a thread launched from your app/use AsyncTask class to do it for you.

The concept of services is to run in the background; By background, the meaning is usually when your app UI is NOT VISIBLE. True, it can be used just like you have (If you remember to stop it) but its just not right, and it consumes resources you shouldn't be using.

If you want to peform tasks on the background of your activity, use AsyncTask.

By the way, onStart is deprecated. When you do use services, implement onStartCommand.

UPDATE:

I think this code will work for you. Add this class (Enclosed in your activity class).

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

Now, in order to control the music, save your BackgroundSound object instead of creating it annonymously. Declare it as a field in your activity:

    BackgroundSound mBackgroundSound = new BackgroundSound();

On your activity's onResume method, start it:

    public void onResume() {
super.onResume();
mBackgroundSound.execute(null);
}

And on your activity's onPause method, stop it:

     public void onPause() {
super.onPause();
mBackgroundSound.cancel(true);
}

This will work.

这篇关于Android的播放音乐的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆