如何通过App连续播放背景音乐?

时间:2014-04-17 06:58:48

标签: android android-music-player

我的Android应用程序中有4个活动。创建第一个活动时,它会在后台启动音乐。现在当用户从第一个活动转到第二个活动时,我想让歌曲继续而不会中断。只有当用户不在应用程序中时,歌曲才会停止。

现在,当我退出一项活动并从下一次活动开始时音乐停止。

3 个答案:

答案 0 :(得分:3)

将播放器作为静态参考保留在后台。然后告诉它您是在移动应用程序内还是移动它。我就是这样做的。我正在使用一个名为DJ的课程。

public class DJ { 
private static MediaPlayer player;
private static boolean keepMusicOn;

public static void iAmIn(Context context){
if (player == null){
player = MediaPlayer.create(context, R.raw.music1);
player.setLooping(true);

try{
player.prepare();
}
catch (IllegalStateException e){}
catch (IOException e){}
}

if(!player.isPlaying()){
player.start();
}

keepMusicOn= false;
}

public static void keepMusicOn(){
keepMusicOn= true;
}

public static void iAmLeaving(){

if(!keepMusicOn){
player.pause();
}
}
}

现在从您的活动中调用这样的DJ。(如果您想保留音乐,请告诉他)

public void onPause() {
super.onPause();
DJ.iAmLeaving();
}

public void onResume(){
super.onResume();
DJ.iAmIn(this); 
}

public void buttonOnClick(View view){
DJ.keepMusicOn();
Intent intent = new Intent(this, TheOtherActivity.class);
startActivity(intent);
}

答案 1 :(得分:2)

我是这样做的,我对结果感到满意:

第一次创建服务:

public class LocalService extends Service
{
    // This is the object that receives interactions from clients. See RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();
    private MediaPlayer player;

    /**
     * Class for clients to access. Because we know this service always runs in
     * the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder
    {
        LocalService getService()
        {
            return LocalService.this;
        }
    }

    @Override
    public void onCreate()
    {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        // We want this service to continue running until it is explicitly stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy()
    {
        destroy();
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return mBinder;
    }


    public void play(int res)
    {
        try
        {
            player = MediaPlayer.create(this, res);
            player.setLooping(true);
            player.setVolume(0.1f, 0.1f);
            player.start();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }


    public void pause()
    {
        if(null != player && player.isPlaying())
        {
            player.pause();
            player.seekTo(0);
        }
    }


    public void resume()
    {
        try
        {
            if(null != player && !player.isPlaying())
            {
                player.start();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }


    public void destroy()
    {
        if(null != player)
        {
            if(player.isPlaying())
            {
                player.stop();
            }

            player.release();
            player = null;
        }
    }

}

第二次,创建一个基本活动并扩展您希望播放背景音乐的所有活动:

public class ActivityBase extends Activity
{
    private Context context = ActivityBase.this;
    private final int [] background_sound = { R.raw.azilum_2, R.raw.bg_sound_5 };
    private LocalService mBoundService;
    private boolean mIsBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        doBindService();
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        try
        {
            if(null != mBoundService)
            {
                Random rand = new Random();
                int what = background_sound[rand.nextInt(background_sound.length)];
                mBoundService.play(what);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        basePause();
    }



    protected void baseResume()
    {
        try
        {
            if(null != mBoundService)
            {
                mBoundService.resume();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }


    protected void basePause()
    {
        try
        {
            if(null != mBoundService)
            {
                mBoundService.pause();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }



    private ServiceConnection mConnection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service. Because we have bound to a explicit
            // service that we know is running in our own process, we can
            // cast its IBinder to a concrete class and directly access it.
            mBoundService = ((LocalService.LocalBinder) service).getService();

            if(null != mBoundService)
            {
                Random rand = new Random();
                int what = background_sound[rand.nextInt(background_sound.length)];
                mBoundService.play(what);
            }
        }

        public void onServiceDisconnected(ComponentName className)
        {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
            mBoundService = null;

            if(null != mBoundService)
            {
                mBoundService.destroy();
            }
        }
    };

    private void doBindService()
    {
        // Establish a connection with the service. We use an explicit
        // class name because we want a specific service implementation that
        // we know will be running in our own process (and thus won't be
        // supporting component replacement by other applications).

        Intent i = new Intent(getApplicationContext(), LocalService.class);
        bindService(i, mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    private void doUnbindService()
    {
        if (mIsBound)
        {
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
        }
    }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        doUnbindService();
    }
}

就是这样,现在你在从ActivityBase扩展的所有活动中都有背景声音。

您甚至可以通过调用basePause()/ baseResume()来控制暂停/恢复功能。

不要忘记在清单中声明服务:

<service android:name="com.gga.screaming.speech.LocalService" />

答案 2 :(得分:1)

这个想法是你不应该从活动本身播放音乐。在Android,活动和其他环境中,有生命周期。这意味着他们将活着......并且死去。当他们死了,他们就再也做不了什么了。

因此,如果您希望音乐能够延长寿命,那么您必须找到一个持续时间超过一个活动的生命周期。

最简单的解决方案是Android服务。你可以在这里找到一个好的主题:Android background music service