2016-06-29 7 views
0

Dies ist die Methode bin using..and wird bei Bedarf anrufen ... in meinem Fall möchte ich das Audio von einer Taste steuern, ob es umschalten oder Knopf ... klicken Sie auf und starten in einer Stopp-TasteAndroid Audio Play und Stop

private void playSound() { 
    if (isFlashLightOn) { 
     mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off); 
    } else { 
     mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on); 
    } 
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 

     @Override 
     public void onCompletion(MediaPlayer mp) { 
      // TODO Auto-generated method stub 
      mp.release(); 
     } 
    });mp.start(); playing=true; 

} 

Antwort

0

eine bearbeitete Version des Codes

private void playSound() { 
    if (isFlashLightOn) { 
     mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off); 
    } else { 
    mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on); 
    } 
    mp.prepareAsync(); //prepares the MediaPlayer 
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 
     @Override 
     public void onPrepared(MediaPlayer mediaPlayer) { 
      //MediaPlayer instance prepared 
      mp.start(); //play the content 
      playing=true;//update the flag 
     } 
    }); 
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mp) { 
      mp.release(); //playback finished 
      playing=false; //update the flag 
     } 
    }); 
} 

weitere Informationen über Mediaplayer here

0

Onclick p AVerwenden:

public void pause(View view) { 

      Toast.makeText(getApplicationContext(), 
        "Pausando..", Toast.LENGTH_SHORT) 
        .show(); 
      if (mp != null && mp.isPlaying()) { 
       mp.pause(); 
      } 
     }//pause 

Onclik Stop-

public void stop(View view) { 
     Toast.makeText(getApplicationContext(), 
       "Stop", Toast.LENGTH_SHORT) 
       .show(); 
     if (mp != null) { 
      mp.stop(); 


     }//if 
    }//stop