如何在Android上播放背景中的流式音频?

时间:2012-10-10 15:02:43

标签: android media-player

我有一个Android应用程序,可以使用MediaPlayer类从Internet播放流式音频。

  

如何让它继续在后台播放音频   用户点击主页按钮运行其他应用程序?

在运行其他应用时,我希望它继续播放音频。

3 个答案:

答案 0 :(得分:12)

您必须使用名为Android Services的内容。

来自文档:

“服务是一个应用程序组件,表示应用程序希望在不与用户交互或为其他应用程序提供功能的情况下执行较长时间运行的操作。”

以下是使用服务帮助您入门的优秀官方指南: http://developer.android.com/guide/components/services.html

这是一个关于构建音频播放器的好教程: http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

以下是构建流式音乐播放器的视频教程: http://www.youtube.com/watch?v=LKL-efbiIAM

答案 1 :(得分:4)

您需要实现一项服务才能在后台播放媒体,而不必将其与开始播放的活动绑定。看看this example

答案 2 :(得分:1)

关键是定义Service.START_STICKY以继续在后台播放:

   public int onStartCommand(Intent intent, int flags, int startId) {
        myMediaPlayer.start();
        return Service.START_STICKY;
    }
  

Service.START_STICKY:如果此服务的进程被杀死了   启动系统将尝试重新创建服务。

这是执行此操作的示例:

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by jorgesys.
 */

/* Add declaration of this service into the AndroidManifest.xml inside application tag*/

public class BackgroundSoundService extends Service {

    private static final String TAG = "BackgroundSoundService";
    MediaPlayer player;

    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "onBind()" );
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.jorgesys_song);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);
        Toast.makeText(this, "Service started...", Toast.LENGTH_SHORT).show();
        Log.i(TAG, "onCreate() , service started...");

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return Service.START_STICKY;
    }

    public IBinder onUnBind(Intent arg0) {
        Log.i(TAG, "onUnBind()");
        return null;
    }

    public void onStop() {
        Log.i(TAG, "onStop()");
    }
    public void onPause() {
        Log.i(TAG, "onPause()");
    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
        Toast.makeText(this, "Service stopped...", Toast.LENGTH_SHORT).show();
        Log.i(TAG, "onCreate() , service stopped...");
    }

    @Override
    public void onLowMemory() {
        Log.i(TAG, "onLowMemory()");
    }
}

启动服务:

Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);

停止服务:

Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);

<强> Complete code of this example.