2016-03-28 5 views
0

Ich verwende den folgenden Code, um Audiodatei (.wav) abzuspielen, aber er spielt die Datei mit Echo (wie zwei Stimmen gleichzeitig abzuspielen), wenn die Aktivität aktiv ist LandschaftsmodusMedia Player spielt Audiodatei (.wav) mit Echo im Landscape-Modus

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 Aktivität ...

Antwort

1

Sie irgendwie die PlayVoice() Methode rufen zweimal. Der Grund dafür, dass Ihre innere if-Anweisung dies nicht verhindert, ist, dass Sie mp = new MediaPlayer(); anrufen müssen, bevor Sie PlayVoice() aufrufen, da andernfalls der erste Aufruf dieser Methode zu einem NullPointerException-Aufruf im if-Zustand führen würde. Da mp jetzt auf eine neue MediaPlayer Instanz verweist, gibt isPlaying()false zurück und der if Block wird erneut ausgeführt, obwohl die vorherige Instanz noch spielt.

Um mehrere Instanzen von MediaPlayer spielen gleichzeitig, instanziiert die MediaPlayer nur einmal in der Deklarationszeile, entfernen Sie die mp = new MediaPlayer(); Linie in PlayVoice() (man könnte es und anderswo haben) und un-Kommentar der mp.reset(); Anruf dort zu verhindern.


Die PlayVoice() Methode aufgerufen zweimal wird, weil man in den Activity ‚s onCreate() Methode zur Landschaft eine Orientierungsänderung anfordern, und Sie Umgang mit nicht-Konfiguration selbst ändert. Dies führt dazu, dass Activity, gestartet im Hochformat, zerstört und neu erstellt wird, was bedeutet, dass onCreate() ein zweites Mal ausgeführt wird, aber die MediaPlayer Instanz in der ersten Activity Instanz spielt noch, wenn eine neue erstellt und in der zweiten Instanz gestartet wird.

Sie können dies verhindern, indem Sie den Activity von Anfang an in Querformat starten. Sie können dies tun, indem Sie android:screenOrientation="landscape" zu dem Tag <activity> im Manifest hinzufügen. Sie können den Anruf setRequestedOrientation() jetzt auch entfernen, da er nicht mehr benötigt wird.

+0

ja ich benutze einige service, wo es zweimal gespielt werden kann, also wie kann ich das verhindern und kann nur einmal in dieser funktion spielen, pelase hilfe –

+0

ich gerade das in meine post bearbeitet. –

+0

Übrigens, ich glaube nicht, dass ich es klar gemacht habe: Sie möchten jedes andere Vorkommen 'mp = new MediaPlayer();' entfernen, mit Ausnahme der einen Instanz in der Deklarationszeile. –