返回列表 發帖

Android App - Play audio

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


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>
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊
Bill Tang     MSN:billtang@openplatform.com.hk
Openplatform Technology Co.,Ltd. 資訊坊科技有限公司  
無線工程施工、方案設計、無線產品、天饋材料、終端設備綜合供應商
Tel: 852-27491011  Fax: 852-81483532

返回列表