Skip to content

Instantly share code, notes, and snippets.

@juehan
Created February 26, 2012 09:52
Show Gist options
  • Save juehan/1915731 to your computer and use it in GitHub Desktop.
Save juehan/1915731 to your computer and use it in GitHub Desktop.
Very Simple Android MP3 Player
package com.audroid.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloMusicActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
MediaPlayer m;
Context c;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnPlay = (Button)findViewById(R.id.buttonPlay);
Button btnStop = (Button)findViewById(R.id.buttonStop);
//Register button click listener
btnPlay.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
//Register button click event
public void onClick(View v){
int id = v.getId();
if(id == R.id.buttonPlay){
play();
}
else if(id == R.id.buttonStop){
stop();
}
else{
//do nothing
}
}
//Play music
public void play(){
c = getApplicationContext();
try {
stop();
m = MediaPlayer.create(c, R.raw.a);
m.setLooping(true);
m.start();
}catch (IllegalStateException e) {
e.printStackTrace();
}
}
//Stop music play
public void stop()
{
try {
if(m != null)
{
m.stop();
m.release();
m = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/buttonPlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/strplay" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/buttonStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/strStop" />
</LinearLayout>
@Smnils
Copy link

Smnils commented Feb 14, 2020

Very simple thanks

@efturtle
Copy link

nice job

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment