简体   繁体   English

在服务类中使用MediaPlayer ...?

[英]Using MediaPlayer in a Service Class…?

I'm making an app, and currently I'm working on adding background music to it. 我正在制作一个应用程序,目前正在为它添加背景音乐。 I've seen a lot of ways to do that, and I've chosen to make it using a Service. 我已经看到了很多方法来做到这一点,并且选择使用服务来实现它。 My problem, however, comes when I call that Service, due to I hear nothing, the music doesn't play! 但是,当我致电该服务时遇到了问题,由于听不到任何声音,因此无法播放音乐! I've compared with another examples, and tried almost everything, but there's no change...Instead meanwhile I'm using an IntentService to play the music (to have at least something), but it isn't pretty good, cos for example when I press the home button, the music continues playing... 我已经与另一个示例进行了比较,并尝试了几乎所有内容,但是没有任何变化……相反,我正在使用IntentService播放音乐(至少有一些内容),但是效果并不好,因为例如,当我按下主屏幕按钮时,音乐会继续播放...

The code of the Service Class is the following: 服务类的代码如下:

    package edu.ub.pis2016.darmas.entrega1;


    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.os.IBinder;
    import android.widget.Toast;


    public class Service_1 extends Service {

        MediaPlayer player;


        public IBinder onBind(Intent arg0) {

            return null;
        }

        @Override
        public void onCreate(){
            super.onCreate();
            player = MediaPlayer.create(this, R.raw.calm);
            player.setLooping(true); // Set looping
            player.setVolume(100,100);
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId){
            player.start();

            return 1;
        }


        @Override
        public void onDestroy(){
            player.stop();
            player.release();
            player = null;
        }


        public void onStop(){
            player.stop();
        }

        public void onPause(){

        }


    }

and I call the Service from one of my activities, by doing: 并且我通过以下活动之一致电“服务”:

Intent intent = new Intent(this, Service_1.class);
startService(intent);

But doesn't work... Instead, here's my code of the IntentService class: 但是不起作用...而是下面是我的IntentService类代码:

    package edu.ub.pis2016.darmas.entrega1;

    import android.app.IntentService;
    import android.content.Context;
    import android.content.Intent;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.os.IBinder;
    import android.view.KeyEvent;
    import android.widget.Toast;

    /*
    *  Service_music Class which extends from IntentService class. We do   this    due to with this latter,
    *  there's no need to implement a thread thanks to it creates by  default (a worker thread),
    *  which runs in the background. Also, this class implements from  Audiomanager, in order to
    *  control the different situations in where the music can be found  through the phone.
    *
    */
    public class Service_music extends IntentService implements AudioManager.OnAudioFocusChangeListener {

        MediaPlayer mp;
        AudioManager audioManager;
        boolean end = false;



        /*
        *  ------------------------------------------------
        *  -            Class Itself Methods              -
        *  ------------------------------------------------
        */

        // Constructor class, required! We create here our worker thread
        public Service_music() {
            super("Service_music_thread");
        }


        public IBinder onBind(Intent arg0) {

            return null;
        }

        @Override
        protected void onHandleIntent(Intent intent) {

            lets_play_music();
            while (end != true){}
        }


        @Override
        public void onDestroy(){
            super.onDestroy(); // It's mandatory to call the super() methods when extending from IntentService
            if (this.mp != null) releaseMediaPlayer();

        }


        /*
        *  ------------------------------------------------
        *  -             Initialize Methods               -
        *  ------------------------------------------------
        */

        // Method to initialize the media player
        private void initializeMediaPlayer(){
            //this.mp = MediaPlayer.create(this, R.raw.calm);
            this.mp = MediaPlayer.create(this, R.raw.barefootandbruisdjamestownstory);
            this.mp.setLooping(true);
            this.mp.start();
        }


        private void initializeAudioManager(){
            this.audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);

            if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // could not get audio focus.
                Toast.makeText(getApplicationContext(), "Ha habido un error al iniciar la musica :(", Toast.LENGTH_SHORT).show();
            }
        }

        /*
        *  ------------------------------------------------
        *  -               Auxiliar Methods               -
        *  ------------------------------------------------
        */

        // This method will carry the task of playing the music, but notice this is only for local media!
        private void lets_play_music(){
            initializeAudioManager();
            initializeMediaPlayer();
            //initializeAudioManager();
            //this.mp.start();
        }


        // Method to release all resources taken by the mp object
        private void releaseMediaPlayer(){
            this.mp.stop();
            this.mp.release();
            this.mp = null;
        }


        /*
        *  ------------------------------------------------
        *  -            Audio Manager Methods             -
        *  ------------------------------------------------
        */

        public void onAudioFocusChange(int focusChange) {
            // Do something based on focus change...
            switch (focusChange){

                // Case if we have gained the focus to play!
                case AudioManager.AUDIOFOCUS_GAIN:
                    if (this.mp == null) initializeMediaPlayer(); // If we had to release the mp by any reason, we re-initialize it!
                    else if(!this.mp.isPlaying()) {
                       this.mp.setLooping(true);  // In theory, it should play looping through infinitely
                       this.mp.start(); // If it's not currently playing, starts!
                    }
                    this.mp.setVolume(1.0f, 1.0f);  // We set the volume!
                    break;

                // Case if we have completely (or almost) lost the focus
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (this.mp.isPlaying()) this.mp.stop(); // If it's currently playing, we have to stop it first
                    end = true;
                    releaseMediaPlayer();  // We release the resources
                    break;

               // Case if we have lost the focus for a short period of time
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    if (this.mp.isPlaying()) this.mp.pause(); // If it's currently playing, we just pause it!
                    break;

                // Case if we have lost the focus but for a tiny piece of time, so we're allowed to continue performing the music but in a quiet state!
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    if (this.mp.isPlaying()) this.mp.setVolume(0.3f, 0.3f); // If it's currently playing, we just set the volume to a quiet level!
                    break;
            }
        }


    }

This latter works, but not the 'AudioManager', and when I press the 'home button' the music continues playing... 后者可以使用,但不能使用“ AudioManager”,当我按下“主页”按钮时,音乐会继续播放...

If someone could help me, or tell me where is the error, or what I'm doing bad, to fix this, I'd be extremely grateful, because I'm turning mad with this... 如果有人可以帮助我,或者告诉我错误出在哪里,或者我做得不好,要解决此问题,我将非常感激,因为我对此很生气。

Two guesses (due to lack of full code): 两个猜测(由于缺乏完整的代码):

Your manifest doesn't contain the service, so it doesn't receive the intent R.raw.value doesn't exist 您的清单不包含该服务,因此它不接收意图R.raw.value不存在

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM