停止Android音频播放器的背景声音

时间:2014-11-24 23:14:15

标签: java android audio android-audiomanager

我在Android音频播放器活动中播放声音。当我暂停那个活动时,声音继续在后台播放。当我恢复音频播放器活动时,我想停止那种声音。 这是我的代码.. 任何人都可以帮助我如何做到这一点。非常感谢任何帮助,谢谢你:)。

public class AndroidBuildingMusicPlayerActivity extends Activity implements
        OnCompletionListener, SeekBar.OnSeekBarChangeListener {

    private ImageButton btnPlay;
    private ImageButton btnForward;
    private ImageButton btnBackward;
    // private ImageButton btnNext;
    // private ImageButton btnPrevious;
    // private ImageButton btnPrevious;
    private ImageButton btnPlaylist;
    private ImageView songimg;
    // private ImageButton btnRepeat;
    // private ImageButton btnShuffle;
    private SeekBar songProgressBar;
    private TextView songTitleLabel;
    private TextView songCurrentDurationLabel;
    private TextView songTotalDurationLabel;
    // Media Player
    private MediaPlayer mp;
    // Handler to update UI timer, progress bar etc,.
    private Handler mHandler = new Handler();;
    private SongsManager songManager;
    private Utilities utils;
    private int seekForwardTime = 5000; // 5000 milliseconds
    private int seekBackwardTime = 5000; // 5000 milliseconds
    private int currentSongIndex = 0;
    private boolean isShuffle = false;
    private boolean isRepeat = false;
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    String[] stringArray = new String[4];

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mediaplayer);

        // All player buttons
        btnPlay = (ImageButton) findViewById(R.id.btnPlay);
        btnForward = (ImageButton) findViewById(R.id.btnForward);
        btnBackward = (ImageButton) findViewById(R.id.btnBackward);
        // btnNext = (ImageButton) findViewById(R.id.btnNext);
        // btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
        btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
        songimg = (ImageView) findViewById(R.id.songimg);
        // btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
        btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
        songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
        songTitleLabel = (TextView) findViewById(R.id.songTitle);
        songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
        songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

        // Mediaplayer
        mp = new MediaPlayer();
        songManager = new SongsManager();
        utils = new Utilities();

        // Listeners
        songProgressBar.setOnSeekBarChangeListener(this); // Important
        mp.setOnCompletionListener(this); // Important

        // Getting all songs list
        songsList = songManager.getPlayList();
        final String[] stringArray = getIntent().getStringArrayExtra("string-array");
        // By default play first song
        playSong(stringArray[0]);
        songTitleLabel.setText(stringArray[1]);
        new DownloadImageTask(songimg).execute(stringArray[2]);
        btnPlaylist.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                final String[] option = new String[] {"Share",
                        "Stop" };
                ArrayAdapter<String> adapters = new ArrayAdapter<String>(
                        AndroidBuildingMusicPlayerActivity.this,
                        android.R.layout.select_dialog_item, option);
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AndroidBuildingMusicPlayerActivity.this);
                builder.setTitle("Choose Action");
                builder.setAdapter(adapters,
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub

                                if (which == 1) {
                                    mp.stop();
                                    finish();
                                }
                                if (which == 0) {
                                    Intent browserIntent = new Intent(
                                            Intent.ACTION_SEND);
                                    browserIntent.setType("text/plain");
                                    browserIntent.putExtra(
                                            android.content.Intent.EXTRA_TEXT,
                                            stringArray[3]);
                                    // ,
                                    // Uri.parse("https://www.youtube.com/watch?v="+ids.get(mPosition)));
                                    startActivity(Intent.createChooser(
                                            browserIntent, "Share Song Link"));
                                }
                            }
                        });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
        /**
         * Play button click event plays a song and changes button to pause
         * image pauses a song and changes button to play image
         * */
        btnPlay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // check for already playing
                if (mp.isPlaying()) {
                    if (mp != null) {
                        mp.pause();
                        // Changing button image to play button
                        btnPlay.setImageResource(R.drawable.btn_play);
                    }
                } else {
                    // Resume song
                    if (mp != null) {
                        mp.start();
                        // Changing button image to pause button
                        btnPlay.setImageResource(R.drawable.btn_pause);
                    }
                }

            }
        });

        /**
         * Forward button click event Forwards song specified seconds
         * */
        btnForward.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // get current song position
                int currentPosition = mp.getCurrentPosition();
                // check if seekForward time is lesser than song duration
                if (currentPosition + seekForwardTime <= mp.getDuration()) {
                    // forward song
                    mp.seekTo(currentPosition + seekForwardTime);
                } else {
                    // forward to end position
                    mp.seekTo(mp.getDuration());
                }
            }
        });

        /**
         * Backward button click event Backward song to specified seconds
         * */
        btnBackward.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // get current song position
                int currentPosition = mp.getCurrentPosition();
                // check if seekBackward time is greater than 0 sec
                if (currentPosition - seekBackwardTime >= 0) {
                    // forward song
                    mp.seekTo(currentPosition - seekBackwardTime);
                } else {
                    // backward to starting position
                    mp.seekTo(0);
                }

            }
        });



    }

    /**
     * Receiving song index from playlist view and play the song
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            currentSongIndex = data.getExtras().getInt("songIndex");
            // play selected song
            playSong(stringArray[0]);
        }

    }

    /**
     * Function to play a song
     * 
     * @param songIndex
     *            - index of song
     * */
    public void playSong(String songpath) {
        // Play song
        try {
            mp.reset();
            mp.setDataSource(songpath);
            mp.prepare();
            mp.start();
            // Displaying Song title
            // String songTitle = songsList.get(songIndex).get("songTitle");
            // songTitleLabel.setText(songTitle);

            // Changing Button Image to pause image
            btnPlay.setImageResource(R.drawable.btn_pause);

            // set Progress bar values
            songProgressBar.setProgress(0);
            songProgressBar.setMax(100);

            // Updating progress bar
            updateProgressBar();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Update timer on seekbar
     * */
    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    /**
     * Background Runnable thread
     * */
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            long totalDuration = mp.getDuration();
            long currentDuration = mp.getCurrentPosition();

            // Displaying Total Duration time
            songTotalDurationLabel.setText(""
                    + utils.milliSecondsToTimer(totalDuration));
            // Displaying time completed playing
            songCurrentDurationLabel.setText(""
                    + utils.milliSecondsToTimer(currentDuration));

            // Updating progress bar
            int progress = (int) (utils.getProgressPercentage(currentDuration,
                    totalDuration));
            // Log.d("Progress", ""+progress);
            songProgressBar.setProgress(progress);

            // Running this thread after 100 milliseconds
            mHandler.postDelayed(this, 100);
        }
    };

    /**
     * 
     * */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromTouch) {

    }

    /**
     * When user starts moving the progress handler
     * */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // remove message Handler from updating progress bar
        mHandler.removeCallbacks(mUpdateTimeTask);
    }

    /**
     * When user stops moving the progress hanlder
     * */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mHandler.removeCallbacks(mUpdateTimeTask);
        int totalDuration = mp.getDuration();
        int currentPosition = utils.progressToTimer(seekBar.getProgress(),
                totalDuration);

        // forward or backward to certain seconds
        mp.seekTo(currentPosition);

        // update timer progress again
        updateProgressBar();
    }

    /**
     * On Song Playing completed if repeat is ON play same song again if shuffle
     * is ON play random song
     * */
    @Override
    public void onCompletion(MediaPlayer arg0) {

        // check for repeat is ON or OFF
        if (isRepeat) {
            // repeat is on play same song again
            playSong(stringArray[0]);
        } else if (isShuffle) {
            // shuffle is on - play a random song
            Random rand = new Random();
            currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
            playSong(stringArray[0]);
        } else {
            // no repeat or shuffle ON - play next song
            if (currentSongIndex < (songsList.size() - 1)) {
                playSong(stringArray[0]);
                currentSongIndex = currentSongIndex + 1;
            } else {
                // play first song
                playSong(stringArray[0]);
                currentSongIndex = 0;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //mp.stop();
    }

    class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            // pd.show();
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            // pd.dismiss();
            bmImage.setImageBitmap(result);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

尝试:覆盖onStop()和onRestart()

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

        if (mp.isPlaying()) {
            mp.stop();
          // or mp.pause();
        }
    }

  @Override
    public void onRestart() {
            super.onRestart();
 if (mp == null) {
        //create mp from current song, for example
        mp = MediaPlayer.create(AndroidBuildingMusicPlayerActivity.this, currentSong);
    }

    mp.start();
}

编辑:

尝试:

@Override
protected void onPause() {
    super.onPause();
    try{
        if (mp.isPlaying()) {
          mp.pause();
    }
    }catch(Exception we){
        we.printStackTrace();
    }

}


 @Override
protected void onResume() {
    super.onResume();
    try{
         mp.start();

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

}

答案 1 :(得分:0)

你应该使用AUDIO FOCUS和onfocuschangelistener来解决你的问题。