2014-11-24 2 views
1

나는 안드로이드 오디오 플레이어 활동에서 소리를 재생하고 있습니다. 그 활동을 일시 중지하면 사운드가 백그라운드에서 계속 연주됩니다. 오디오 플레이어 활동을 다시 시작할 때 그 소리를 멈추고 싶습니다. 여기 사람이 많이 주시면 감사하겠습니다 내가 this.any 도움을 할 수있는 방법에 도움이 될 수 있습니다 .. 내 코드,안드로이드 오디오 플레이어의 배경 소리를 중지

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); 
     } 
    } 
} 

답변

0

시도를 :) 감사합니다 :

@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(); 
} 
을 (중지시 재정의)와 onRestart()

편집 :

시도 : 오디오 FOCUS를 사용해야합니다

@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(); 
    } 

} 
+0

- 대신 이동 중지()의) onPause를 (무시하려고 - -이 작업을해야을 당신이 무시되는 클래스 AndroidBuildingMusicPlayerActivity –

+0

작동하지 않습니다 – Wildroid

+0

@TashenJazbi을 할 경우 mp.stop() 또는 MP mp.release()가 작동하지 않는다면 mp onRestart() 또는 onResume()을 만들어야한다 - mp가 null이 될 수있다 – Wildroid

0

onfocuschangelistener를 사용하면 문제를 해결할 수 있습니다.

가 작동하지 않는 부분 @TashenJazbi :(
관련 문제