每次移动方向改变时,声音都会反复播放

时间:2018-04-28 09:20:08

标签: java android eclipse

当媒体播放器播放声音并且每次手机的方向从纵向更改为横向或横向更改为纵向时,每次更改方向时声音都会再次开始。

如何在不播放新声音的情况下继续播放当前正以其他方向播放的相同声音?

这是我的代码:

public void SoundStuff(final Bundle savedInstanceState) {

    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_viewpager_example);

    mP = MediaPlayer.create(this, R.raw.c101);

    //btn1 = (Button) findViewById(R.id.btnPlay);
    tgbtn1 = (ToggleButton) findViewById(R.id.imageButton2);
    btnstop1 = (Button) findViewById(R.id.button1);

    tgbtn1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                // The toggle is enabled
                 try {
                     mP.start();
                      //tgbtn1.setVisibility(View.GONE);

                 }
                 catch (Exception exception) {
                     Log.v("exception:play", exception.toString());
                 }
             }
             else {

                 // The toggle is disabled
                 try {
                     mP.pause();
                 }
                 catch (Exception exception) {
                     Log.v("exception:pause", exception.toString());
                 }
             }
         }
     });


     btnstop1.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View v) {
             if(mP.isPlaying()){
                 mP.stop();
             }

             SoundStuff(savedInstanceState);
             ZoomImageView mViewPager = (ZoomImageView) findViewById(R.id.view_pager);

             Btn1ImageAdapter adapter = new Btn1ImageAdapter();
             mViewPager.setAdapter(adapter);
         }
     });

1 个答案:

答案 0 :(得分:0)

嗯,当方向发生变化时,将重新创建活动,以便您可以通过在清单文件中添加活动中的以下行来手动处理方向更改,

android:configChanges="orientation|screenSize"

这会在重新创建时阻止您的活动,并且只会在更改方向时恢复。试试这个。

使用上述解决方案时,无需专门为横向模式定义布局。

但是,如果你需要定义它,那么在横向和&纵向模式,您可以在下面的方法中简单地定义这些更改。

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}