【问题标题】:Error In Music App(Media Player) in Android studioAndroid工作室中的音乐应用程序(媒体播放器)错误
【发布时间】:2015-10-31 22:36:08
【问题描述】:

我正在尝试在 android studio 中制作音乐应用。我的应用程序运行良好,只是它有一个小错误。在我的主要活动中,我有一个从资源文件夹中的原始文件夹导入的歌曲列表。我的第二个窗口是一个 NowPlaying java 文件,我可以在其中暂停、转发和查看歌曲的歌词。

当我从 Main Activity 播放第一首歌曲时,它运行良好。但是,当我想在播放第一首歌曲时播放第二首歌曲时,第二首歌曲会在第一首歌曲之上播放。歌词更新,搜索栏更新,但两首歌一起播放。但是,当我暂停第一首歌曲,返回主活动并播放第二首歌曲时,不会发生这种情况。 我用了 :

if(song != null){
    if(song.isPlaying()){ 
        song.reset(); song = null;   
    }
}

我知道我的 NowPlaying.java 文件中有一个错误:所以这是整个代码:

PS。我只是在学习过程中。

MediaPlayer song = null;
SeekBar seekBar;
Intent intent = getIntent();


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_now_playing);

    seekBar = (SeekBar) findViewById(R.id.seekBar);
    //String selectedSong =  getIntent().getExtras().getString("selectSong");


    selectSong();


    //for pause button
    pauseButton();

    //for songtile
    getSongtitle();

    getSongList();
    getNextButton();
    getPreviousButton();

} // end of onCreate method


/**
 * Method for selecting the song
 * Moves to startSong method
 */
public void selectSong(){


    TextView lyricsBox = (TextView) findViewById(R.id.lyricsBox);
    lyricsBox.setMovementMethod(new ScrollingMovementMethod());
    String nextPlay = intent.getStringExtra("playSong");

    if(song != null){
        if(song.isPlaying()){
            song.reset();
            song = null;
        }
    }

    if (nextPlay.equals("Demons")) {
        song = MediaPlayer.create(this, R.raw.demons);
        lyricsBox.setText(R.string.demonsLyrics);

    } else if (nextPlay.equals("Black Space")) {
        song = MediaPlayer.create(this, R.raw.blankspace);
        lyricsBox.setText(R.string.blankspaceLyrics);

    } else if (nextPlay.equals("Case 420")) {
        song = MediaPlayer.create(this, R.raw.case420);
        lyricsBox.setText(R.string.case420Lyrics);
    }
    else if(nextPlay.equals("Jalma")){
        song = MediaPlayer.create(this, R.raw.jalma);
        lyricsBox.setText(R.string.jalmaLyrics);
    }
    else if(nextPlay.equals("Parelima")){
        song = MediaPlayer.create(this, R.raw.parelima);
        lyricsBox.setText(R.string.parelimaLyrics);
    }

    else if(nextPlay.equals("Mero Balyakal Ko Sathi")){
        song = MediaPlayer.create(this, R.raw.balyakalsathi);
        lyricsBox.setText(R.string.balyakalSathi);
    }

    else if(nextPlay.equals("Euta Sathi")){
        song = MediaPlayer.create(this, R.raw.eutasathi);

    }
    else if(nextPlay.equals("Audai Jadai")){
        song = MediaPlayer.create(this, R.raw.audaijadai);

    }
    else if(nextPlay.equals("Cheerleader")){
        song = MediaPlayer.create(this, R.raw.cheerleader);

    }



    // to start playing the song
    startButton();
}



//method to make sure seekbar updates till song ends
Runnable run = new Runnable() {
    @Override
    public void run() {
        getseekBar();
    }
};

/**
 * Method to start song (play the song)
 *
 */
public void startButton() {
        song.start();
    //to update seek bar
    getseekBar();
}




/**
 * Method to update the seekbar.
 * implement touch in seekbar to change song position
 */
public void getseekBar() {
    seekBar.setMax(song.getDuration());
    seekBar.setProgress(song.getCurrentPosition());
    seekBar.postDelayed(run, 1000);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        int seek_to;
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
             seek_to = progress;

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            song.seekTo(seek_to);
        }
    });
}


/**
 * Method for pause Button
 * to pause song once clicked and change button background to play image
 * Again play the song if the button is pressed again. and change background back to pause image
 */
public void pauseButton(){
    final Button playButton = (Button) findViewById(R.id.playButton);

    playButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (song.isPlaying()) {
                playButton.setBackgroundResource(R.drawable.playbutton);
                song.pause();

            } else {
                playButton.setBackgroundResource(R.drawable.pausebutton);
                song.start();

            }

        }
    });
}

/**
 * Method to get the song title from first java file and display in the title
 */
public void getSongtitle(){

    Intent intent = getIntent();
    String nextPlay = intent.getStringExtra("playSong");
    TextView Songtitle = (TextView) findViewById(R.id.Songtitle);
    Songtitle.setText(nextPlay);
}

/**
 * Method for song list button
 * Goes back to the first java file once the button is cliked,
 * displays the song list
 */

public void getSongList(){

    Button lyricsButton = (Button) findViewById(R.id.lyricsButton);
    lyricsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(NowPlaying.this, MainActivity.class));
        }
    });

}

/**
 * Method for next button
 * the song skips every 10 seconds once clicked
 */

public void getNextButton(){

    Button nextButton = (Button) findViewById(R.id.nextButton);
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int startTime = song.getCurrentPosition();
            int forwardTime = 10000;
            startTime += forwardTime;
            if(startTime <= song.getDuration()){

                song.seekTo(startTime);
            }

            else{
                song.stop();

            }


        }
    });

} // end of getNextButton


/**
 * Method for previous button
 * the song skips back 10 seconds once clicked
 */
public void getPreviousButton(){

    Button previousButton = (Button) findViewById(R.id.previousButton);
    previousButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int startTime = song.getCurrentPosition();
            int previousTime = 10000;
            startTime -= previousTime;

            if(startTime >= 0){
                song.seekTo(startTime);
            }
           else{
               song.seekTo(0);
                song.start();
            }
        }
    });
}

主要活动代码:

公共类 MainActivity 扩展 AppCompatActivity {

 String[] songList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    populateList();
}

private void populateList(){
     songList = new String[] {"Jalma", "Demons", "Parelima", "Mero Balyakal Ko Sathi", "Audai Jadai",
             "Case 420", "Euta Sathi", "Cheerleader"};

    ListAdapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            songList);

    ListView theList = (ListView) findViewById(R.id.theList);
    theList.setAdapter(arrayAdapter);

    theList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView theList = (ListView) findViewById(R.id.theList);
            startActivity(new Intent(MainActivity.this, NowPlaying.class));
           String selectedSong = (String) (theList.getItemAtPosition(position));

            Intent toSecondActivity = new Intent(getApplicationContext(), NowPlaying.class);

            toSecondActivity.putExtra("playSong", selectedSong);
            startActivity(toSecondActivity);

        }
    });


}

}

【问题讨论】:

  • 请贴出 MainActivity.java 的代码
  • 你能把 Log.d 放到 onCreate() 看看它被调用了多少次。

标签: android android-mediaplayer audio-player android-music-player


【解决方案1】:
protected void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_now_playing);
    .......

    @Override
    public void onDestroy(){
       if(song.isplaying())
       {
          song.pause();
          song.release();
       }
       super.onDestroy();
    }
}

您并没有销毁此 Activity 的实例,当您暂停歌曲时,它再次仅以该 Activity 开始,因此请确保您销毁此 Activity 的实例。

【讨论】:

    【解决方案2】:

    如果没有 MainActivity 类,我无法确定,但您似乎不会在 NowPlaying 中使用同一个 MediaPlayer 实例,所以我只能假设您已经为这两个活动创建了一个新实例。

    这可能意味着原始实例在第一个 Activity 中仍然处于活动状态。

    如果是这样,您可以在切换活动之前销毁 MediaPlayer 的 MainActivity 实例,或者在两个活动中使用相同的实例。

    我会推荐第二个选项,如果您只想一次播放一首歌曲,这是有道理的,那么请查看 Singleton 类。我相信这在这种情况下会很有效。

    http://www.javaworld.com/article/2073352/core-java/simply-singleton.html

    编辑:

    试一试,

    theList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedSong = (String) (theList.getItemAtPosition(position));
    
            Intent toSecondActivity = new Intent(MainActivity.this, NowPlaying.class);
            toSecondActivity.putExtra("playSong", selectedSong);
            startActivity(toSecondActivity);
    
        }
    });
    

    您需要将列表设为最终状态

    【讨论】:

    • 能否请您检查主要活动代码并帮助我
    • 我已经编辑了我的帖子,你应该阅读这篇文章来解释为什么你不应该像以前那样使用 getApplicationContext。 stackoverflow.com/questions/33447762/…
    • 我试过了。但它没有用。选择第二首歌曲后,如何销毁以前的 Mediaplayer 实例。我尝试了 mediaplayer.reset() 方法和释放方法
    【解决方案3】:
    I am also facing the same issue.Songs are playing on top of each other. Finally I found the answer from a video.
    https://www.youtube.com/watch?v=4DC4XFWVFls
    
    
    //For Play Button OnClick Listener
    
    public void onClick(View v) {
    
                    if(mediaPlayer !=null)
                    {
                        mediaPlayer.release();
                    }
                    mediaPlayer = MediaPlayer.create(context, songList.getSong());
                    mediaPlayer.start();
    }
    
    //For Stop Button
    
     public void onClick(View v) {
                    mediaPlayer.stop();
                }
    
    This code worked properly for me.
    

    【讨论】:

    • 此代码不起作用,因为您有两个 onClick(View v) 相同的方法。
    • @arcticwhite.. 我有两个按钮用于播放和停止
    • 是的,您有两个按钮,但您也有两个相同的方法。那么你的按钮怎么知道你点击了哪一个呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多