如何在Android应用程序中播放背景音乐? [英] How to play music in the background in an android app?

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

问题描述

我想在我的应用程序中播放音乐而不管应用程序中发生了什么。我试图用服务来实现它。这是 MyService.class

I want in my application, music playing regardless of what happening in application. I am trying to implement it with Service. Here is the MyService.class

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MyService extends Service implements MediaPlayer.OnPreparedListener {

    MediaPlayer mMediaPlayer = null;
    private static final String ACTION_PLAY = "com.example.action.PLAY";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals(ACTION_PLAY)) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.theme_song);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.prepareAsync(); // prepare async to not block main thread
            return 1;
        } else {
            return 0;
        }
    }

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

有什么可以帮我解决一下我如何使用<$在MyActivity中使用c $ c> Service 以及需要在 MyService.class 中定义哪些其他方法才能获得正确的结果。

Could you please help me about how I use Service in MyActivity and what other methods need to be defined in MyService.class to have the right result.

推荐答案

  public class BackGroundMusic extends Service {
MediaPlayer mediaPlayer;
AudioManager audioManager;
int volume;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    mediaPlayer = MediaPlayer.create(this, R.raw.tune);
    mediaPlayer.start();
    return super.onStartCommand(intent, flags, startId);
}


@Override
public boolean stopService(Intent name) {

    return super.stopService(name);
}

@Override
public void onDestroy() {
    super.onDestroy();
    mediaPlayer.stop();
    mediaPlayer.release();
    mediaPlayer = null;

}
   }

如果你需要玩音乐

startService(new Intent(MainActivity.this, BackGroundMusic.class))

如果你想停止音乐

    stopService(new Intent(MainActivity.this, BackGroundMusic.class)).. 

希望它有所帮助!

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

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