【问题标题】:media player plays audio file (.wav) with echo in Landscape mode媒体播放器在横向模式下播放带有回声的音频文件 (.wav)
【发布时间】:2016-07-15 09:06:38
【问题描述】:

我正在使用以下代码播放音频文件 (.wav),但是当活动处于横向模式时,它会使用 Echo 播放文件(就像同时播放两个声音)。

public class Find_n_Display_StationActivity extends Activity 
{
 GPSTracker gps;
 TextView txtvw,locNameTV;
 boolean calculating_distance=false;
 ArrayList<String>data=new ArrayList<String>();
 ArrayList<String>latArray=new ArrayList<String>();
 ArrayList<String>longArray=new ArrayList<String>();
 MySQLiteHelper db = new MySQLiteHelper(this);

 ImageView profileIV;
 PendingIntent intent;
 String reached_station="empty";
 MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.find_n__display__statn_activity);

    txtvw=(TextView)findViewById(R.id.textView2);
    locNameTV=(TextView)findViewById(R.id.textView1);
    profileIV=(ImageView)findViewById(R.id.image11);


    profileIV.setVisibility(View.GONE);

    //Put in LANDSCAPE MODE...
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);     



    //Show FULL-SCREEN Activity
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

     //Calling/Starting Thread to Handl Uncaught Exeption
     Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);  

        //(((( This will retrieve DATA from service to this Activity ))))
        gps = new GPSTracker(this);
         LocalBroadcastManager.getInstance(this.getApplicationContext()).registerReceiver(
             mMessageReceiver, new IntentFilter("GPSLocationUpdates"));

       //  mp=new MediaPlayer();

}//EOF Oncreate Method...

//(((( This Function is Called if App Crash, So, App is start Automatically after crash ))))
 private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler() 
 {
        public void uncaughtException(Thread thread, Throwable ex) 
        {
            Intent i=new Intent(getApplicationContext(),MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }
 };


// ((((  This Class Get Data From Service class GPSTracker.class() ))))
 private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() 
        {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Get extra data included in the Intent
                String message = intent.getStringExtra("Status");
                Bundle b = intent.getBundleExtra("Location");
             Location   lastKnownLoc = (Location) b.getParcelable("Location");
                if (lastKnownLoc != null) 
                {
                    String s1=String.valueOf(lastKnownLoc.getLatitude());
                    String s2=String.valueOf(lastKnownLoc.getLongitude());

                double  current_lat=Double.parseDouble(s1);
                double  current_long=Double.parseDouble(s2);
                 txtvw.setText("____________________________\n\n\n"+current_lat+"\n"+current_long);
                 //showtoast("You have changed your Location");

               if(calculating_distance==false)
                {
                    calculating_distance=true;

                    FindDistance(current_lat,current_long);
                }

                 Turn_On_Screen();
                }
          }};
private String  stationPlayed="empty";


@SuppressWarnings("deprecation")
public void Turn_On_Screen()
{
    WakeLock screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
             PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        screenLock.acquire();

        //later
        //screenLock.release();
}

          //(((( Find Distance Betwee All Points ))))))
public void FindDistance(double current_lat,double current_long)
{
    Move_App_Back_to_ForeGround();

     ArrayList<String>stationNameArray=new ArrayList<String>();
     ArrayList<String>imageArray=new ArrayList<String>();
     ArrayList<String>voiceArray=new ArrayList<String>();

     imageArray=db.Get_ImageList();
     voiceArray=db.Get_VoiceList();

     stationNameArray=db.Get_StionNameAraay();

    latArray=db.Get_LatAraay();
    longArray=db.Get_LongAraay();

    float smallest_dis=10000;
    String next_station="";
    boolean found_station=false;

    for(int i=1;i<latArray.size();i++)
    {
        float lat1 = Float.parseFloat(latArray.get(i));
        float long1 = Float.parseFloat(longArray.get(i));

       float dis=FindDistance((float)current_lat,(float)current_long,lat1, long1);
        if(dis<smallest_dis)
        {
            smallest_dis=dis;
            next_station=stationNameArray.get(i);

        }
       if(dis<=50)
       {
          Set_Pic_n_Voice(imageArray.get(i),voiceArray.get(i),stationNameArray.get(i));
            //  showtoast("station-name="+ stationNameArray.get(i));
         break;          
       }

    }
    locNameTV.setText("You are Heading towards Station="+next_station+"\n You are only "+smallest_dis+" Meter away...");

    calculating_distance=false;

}


public void Set_Pic_n_Voice(String image,final String voice,final String station_name)
{
    DisplayImage(image);

        if(!reached_station.equalsIgnoreCase(station_name))
         reached_station=""+station_name; //Don't play voice for same station just display pic always

    //Wait for 4 seconds to play this voice
    Runnable r = new Runnable() 
    {

        public void run()
        {   
            if(!stationPlayed.equalsIgnoreCase(station_name))
            {
               PlayVoice(voice);
               stationPlayed=station_name;
            }
        }
    };

    android.os.Handler h = new android.os.Handler();
    h.postDelayed(r, 5000);// */



}


//(((( Displaying Picture For the Station ))))
public void DisplayImage(String image)
{
    profileIV.setVisibility(View.VISIBLE);

        File imageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"Bus_StationApp_Folder/Images",image);

        if (imageFile.exists()) 
        {

    File imgFile = new File(imageFile.getAbsolutePath()); // path of your file
    Picasso.with(this).load(Uri.fromFile(new File(imageFile.getAbsolutePath()))).into(profileIV);
        /*  
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(imgFile);
                } catch (FileNotFoundException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                BitmapFactory.Options options = new BitmapFactory.Options();
                //options.inSampleSize = 8;
                //options.inPurgeable = true;
               // options.inScaled = true;
                Bitmap bm = BitmapFactory.decodeStream(fis, null,options);
              profileIV.setImageBitmap(bm);//*/
         }
        else
            profileIV.setImageResource(R.drawable.default_station_pic);

}


//(((( Playing Voice For The Station )))))) 
public void PlayVoice(String voice)
{

    calculating_distance=true;

//  Play_Audio_File ob=new Play_Audio_File(this);
    //ob.PlayVoice(voice);

     File voiceFile = new File(Environment.getExternalStorageDirectory()+File.separator+"Bus_StationApp_Folder/Voices",voice);

    if (voiceFile.exists()) 
    {


     if(!mp.isPlaying())
       {  

          mp.reset();

        try {
            mp.setDataSource(voiceFile.getAbsolutePath());
            mp.prepare();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

         mp.start();
       }
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() 
        {
            public void onCompletion(MediaPlayer mp) 
            {
                calculating_distance=false;
            }
        });
    }
    else            
    {   
        //mp.reset();
         mp= MediaPlayer.create(this, R.drawable.default_station_voice);
         if(!mp.isPlaying())
          { 

           mp.start();
          }
         mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() 
         {
                public void onCompletion(MediaPlayer mp) 
                {
                    calculating_distance=false;
                }
            });

    }

    //*/ 


}

        //((((( Find distance between two geolocation  )))
public float FindDistance(float lat1, float lng1, float lat2, float lng2)
        {
             double earthRadius = 6371000; //meters
                double dLat = Math.toRadians(lat2-lat1);
                double dLng = Math.toRadians(lng2-lng1);
                double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                           Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                           Math.sin(dLng/2) * Math.sin(dLng/2);
                double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                float dist = (float) (earthRadius * c);

                return dist;

        }


//((( Move App To Screen from Background ))))
public void Move_App_Back_to_ForeGround()
{
    boolean foregroud=false;
    try
    {
     foregroud = new ForegroundCheckTask().execute(getApplicationContext()).get();
    } catch (InterruptedException e) 
    {   e.printStackTrace();
    }
    catch (ExecutionException e) 
    {
        e.printStackTrace();
    }

    if(!foregroud)
    {
    //Open Activity IF it is in Background...
    Intent it = new Intent("intent.my.action");
    it.setComponent(new ComponentName(this.getPackageName(), Find_n_Display_StationActivity.class.getName()));
    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.getApplicationContext().startActivity(it);


    }
}

class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

      @Override
      protected Boolean doInBackground(Context... params) {
        final Context context = params[0].getApplicationContext();
        return isAppOnForeground(context);
      }

      private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
          return false;
        }
        final String packageName = context.getPackageName();
        for (RunningAppProcessInfo appProcess : appProcesses) {
          if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
            return true;
          }
        }
        return false;
      }
    }


//SHOW-TOAST-MESSAGE
public void showtoast(String str)
{
    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}

public void OnBackPressed()
{

}

}//EOF活动...

【问题讨论】:

    标签: android android-mediaplayer


    【解决方案1】:

    您以某种方式调用了PlayVoice() 方法两次。你的内部if 语句不能阻止这种情况的原因是,你必须在调用PlayVoice() 之前调用mp = new MediaPlayer();,否则第一次调用该方法会导致mp.isPlaying() 调用中的NullPointerException if 条件。由于mp 现在指向一个新的MediaPlayer 实例,isPlaying() 返回false,并且if 块再次执行,即使前一个实例仍在播放。

    为防止MediaPlayer 的多个实例同时播放,请在声明行中仅将MediaPlayer 实例化一次,删除PlayVoice() 中的mp = new MediaPlayer(); 行(以及您可能拥有的任何其他位置),然后取消注释mp.reset(); 在那里打电话。


    PlayVoice() 方法被调用了两次,因为您在 ActivityonCreate() 方法中请求将方向更改为横向,而您自己没有处理配置更改。这导致以纵向模式启动的Activity 被销毁并重新创建,这意味着onCreate() 第二次运行,但在第一个Activity 实例中启动的MediaPlayer 在创建新实例时仍在播放并从第二个实例开始。

    您可以通过强制Activity 从一开始就以横向启动来防止这种情况发生。您可以通过将android:screenOrientation="landscape" 添加到清单中的&lt;activity&gt; 标记来实现此目的。您现在也可以删除 setRequestedOrientation() 调用,因为它不再需要。

    【讨论】:

    • 是的,我正在使用一些可以播放两次的服务,所以我该如何防止这种情况并且只能在此功能中播放一次,请帮助
    • 顺便说一句,我想我并没有说清楚:除了声明行中的一个实例化之外,您想删除任何其他出现的 mp = new MediaPlayer();
    • 您是通过“onCreate”还是任何 Activity 生命周期方法调用“PlayVoice”?
    • @RuchiraRandana OP 已经声明他们有一个Service 将多次调用PlayVoice()。我已经为此提供了修复程序。
    • @MikeM。感谢您的评论。我看到 cmets 中提到了这一点!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多