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

问题描述

我想要在我的应用程序中,乐谱播放,无论应用程序中发生什么.我试图用Service实现它.这是 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();
    }
}

可以帮我帮助我如何在yyactivity中使用Service,以及在 myservice.class 中需要定义的其他方法是正确的结果.

推荐答案

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)).. 

其他推荐答案

1.制作背景服务

package service;

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.support.annotation.Nullable;
import java.io.IOException;


public class BackgroundSoundService extends Service {

    MediaPlayer mPlayer = null;
    private final static int MAX_VOLUME = 100;
    Context context;
    AudioManager.OnAudioFocusChangeListener afChangeListener;


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

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

        int musicflag = (int) intent.getExtras().get("songindex");
        if (musicflag == 1) {
            playMusic(R.raw.s1_pondambience);
        } else {
            playMusic(R.raw.s2_integrative_music);
        }
        return Service.START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }
    }

    public void onTaskRemoved(Intent rootIntent) {
        stopSelf();
    }

    /*
    * playmusic custom method for manage two different background sounds for application
    * */

    public void playMusic(int musicFile) {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                try {
                    mPlayer.stop();
                    mPlayer.release();
                    mPlayer = MediaPlayer.create(this, musicFile);

                    AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

                    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        // Start playback.
                        mPlayer.setLooping(true);
                        final float volume = (float) (1 - (Math.log(MAX_VOLUME - 85) / Math.log(MAX_VOLUME)));
                        mPlayer.setVolume(volume, volume);
                        mPlayer.start();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    mPlayer = MediaPlayer.create(this, musicFile);

                    AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

                    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        // Start playback.
                        mPlayer.setLooping(true);
                        final float volume = (float) (1 - (Math.log(MAX_VOLUME - 85) / Math.log(MAX_VOLUME)));
                        mPlayer.setVolume(volume, volume);
                        mPlayer.prepare();
                        mPlayer.start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } else {
            try {
                mPlayer = MediaPlayer.create(this, musicFile);

                AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

                if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                    // Start playback.
                    mPlayer.setLooping(true);
                    final float volume = (float) (1 - (Math.log(MAX_VOLUME - 85) / Math.log(MAX_VOLUME)));
                    mPlayer.setVolume(volume, volume);
                    mPlayer.start();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
    * MediaPlayer methods
    * */

    public void pauseMusic() {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            length = mPlayer.getCurrentPosition();

        }
    }

    public void resumeMusic() {
        if (mPlayer.isPlaying() == false) {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }

    public void stopMusic() {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }

    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }
        return false;
    }

}

并随时启动和停止服务.

2.开始使用以下方法

 private void startBackMusic() {
        Intent musicintent = new Intent(MenuActivity.this, BackgroundSoundService.class);
        musicintent.putExtra(EXTRA_SONGINDEX, 1);
        startService(musicintent);
    }

3.停止使用以下方法

 private void stopBackMusic() {
          Intent musicintent = new Intent(MenuActivity.this, BackgroundSoundService.class);
            stopService(musicintent);
    }

本文地址:https://www.itbaoku.cn/post/978365.html