ว่างๆ ไม่มีอะไรทำเลยเอาโค้ดสำหรับไว้ฟังเพลงเผื่อว่าใครต้องการเขียนโปรแกรมสำหรับการฟังเพลง หรือการเล่นเสียงใน android ซึ่งผมว่ามันทำได้ง่ายมากเนื่องจา่ก api ที่ให้มาสามารถที่จะทำให้เราเขียนเจ้าโปรแกรมฟังเพลงนี้ได้อย่าง่ายดาย โดยในส่วนี้เป็นโค้ดที่ผมไปหามาจากใน anddev.org ส่วนกระทุ้ไหนผมจำไม่ได้ละเพราะว่าผมเอาโึค้ดมาป่นๆ กันแล้วเขียนเองบ้างลอกเขามาบ้างแต่ยังไงก็ให้ credit anddev.org นะครับเอาเป็นว่าไปดู source กันดีกว่าครับ
MusicPlayer.java
import java.io.IOException; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.atm.R; public class MusicPlayer extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.music_player); // Find the Button from the xml-file. Button cmd_play = (Button) this.findViewById(R.id.cmd_play); cmd_play.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { MediaPlayer mp = MediaPlayer.create(MusicPlayer.this, R.raw.fish); try { mp.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.start(); // i.e. react on the end of the music-file: mp.setOnCompletionListener(new OnCompletionListener() { // @Override public void onCompletion(MediaPlayer arg0) { // File has ended !!! Wink } }); } }); } }
music_player.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/cmd_play" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Play the music !!!" /> </LinearLayout>
หลังจากนั้นก็ทำการเลือกเพลงมาซักเพลงครับ สมมุติว่าเป็น fish.mp3 นะครับ ผมก็ทำการ copy file ไปไว้ที่ raw ครับก็เป็นอันว่าเรียบร้อยสำหรับคนที่เล่นแล้วบอกว่า อ้าว เปิดแล้วไม่มีเสียงมันเสียหรือเปล่า อาจจะเป็นเพราะว่าเรายังไม่ได้ทำการตั้งค่าให้ emulator รู้จักเสียงครับก็ให้เข้่าไปแก้ใน Addition Emulator command line เพิ่มในส่วนนี้ครับ
-audio winaudio
แค่นี้ก็ฟังเพลงได้แล้วครับ
63 views


ทดสอบ
i always enjoy to do blog hopping and i stumbled upon your blog -*;”:,