Board logo

標題: Android App - Play audio [打印本頁]

作者: admin    時間: 2012-1-27 14:01     標題: Android App - Play audio

我們會利用 Android SDK 的 mediaplayer 去開始/停止播放聲音

[attach]1003[/attach]
playaudio2Activity.Java 內容

package sample.playaudio2;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Playaudio2Activity extends Activity {
    /** Called when the activity is first created. */
        
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
Button b;
MediaPlayer mp;

@Override

public void onCreate(Bundle savedInstanceState) {     
super.onCreate(savedInstanceState);     
setContentView(R.layout.main);      
b = (Button) this.findViewById(R.id.playSound);  
}

public void butPlayClick(View view)
   {
  mp = MediaPlayer.create(getBaseContext(), R.raw.robotrack);   
  mp.setLooping(false);  // may not be needed
  mp.start();      
  Toast.makeText(this, isPlaying, Toast.LENGTH_SHORT).show();
  b.setClickable(false);
  mp.setOnCompletionListener(new OnCompletionListener() {
      public void onCompletion(MediaPlayer mp) {     
         mp.release();   
         b.setClickable(true);
     }                 
   });     //   setOnCompletionListener
};         //   butPlayClick

public void butStopClick(View view)  {
   mp.pause();
   Toast.makeText(this, notPlaying, Toast.LENGTH_SHORT).show();
   b.setClickable(true);
   }

public static String getNotplaying() {
return notPlaying;
}

public static String getIsplaying() {

return isPlaying;
}

}

把robotrack.mp3 放入 res\raw 內

main.xlm 內容
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/playSound"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/playsound"
        android:onClick="butPlayClick"
         />

    <Button
        android:id="@+id/stopSound"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stopsound"
        android:onClick="butStopClick"
         />

strings.xml 內容

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Playaudio2Activity!</string>
    <string name="app_name">;Play Audio</string>
    <string name="playsound">;Play Sound</string>
    <string name="stopsound">Stop</string>
</resources>

</LinearLayout>




歡迎光臨 How2Do (http://forum.how2do.com.hk/) Powered by Discuz! 7.2