Play a sound : Sound « Media « Android






Play a sound

     
package app.test;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class PlayActivity extends Activity implements MediaPlayer.OnCompletionListener {
    
    Button mPlay;
    MediaPlayer mPlayer;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mPlay = new Button(this);
        mPlay.setText("Play Sound");
        mPlay.setOnClickListener(playListener);
        
        setContentView(R.layout.main);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mPlayer != null) {
            mPlayer.release();
        }
    }
    
    private View.OnClickListener playListener = new View.OnClickListener() {
        
        @Override
        public void onClick(View v) {
            if(mPlayer == null) {
                try {
                    mPlayer = MediaPlayer.create(PlayActivity.this, R.raw.sound);
                    mPlayer.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mPlayer.stop();
                mPlayer.release();
                mPlayer = null;
            }
        }
    };

    @Override
    public void onCompletion(MediaPlayer mp) {
        mPlayer.release();
        mPlayer = null;
    }
    
}

//PlayerActivity.java
package app.test;

import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.MediaController;

public class PlayerActivity extends Activity implements MediaController.MediaPlayerControl, MediaPlayer.OnBufferingUpdateListener {
    
    MediaController mController;
    MediaPlayer mPlayer;
    ImageView coverImage;
    
    int bufferPercent = 0;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        coverImage = (ImageView)findViewById(R.id.coverImage);
        
        mController = new MediaController(this);
        mController.setAnchorView(findViewById(R.id.root)); 
    }
    
    @Override
    public void onResume() {
        super.onResume();
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(this, Uri.parse("http://asdf.org/a.mp3"));
            mPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        coverImage.setImageResource(R.drawable.icon);
        
        mController.setMediaPlayer(this);
        mController.setEnabled(true);
    }
    
    @Override
    public void onPause() {
        super.onPause();
        mPlayer.release();
        mPlayer = null;
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mController.show();
        return super.onTouchEvent(event);
    }
    @Override
    public int getBufferPercentage() {
        return bufferPercent;
    }

    @Override
    public int getCurrentPosition() {
        return mPlayer.getCurrentPosition();
    }

    @Override
    public int getDuration() {
        return mPlayer.getDuration();
    }

    @Override
    public boolean isPlaying() {
        return mPlayer.isPlaying();
    }

    @Override
    public void pause() {
        mPlayer.pause();
    }

    @Override
    public void seekTo(int pos) {
        mPlayer.seekTo(pos);
    }

    @Override
    public void start() {
        mPlayer.start();
    }
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        bufferPercent = percent;
    }
    public boolean canPause() {
        return true;
    }
    public boolean canSeekBackward() {
        return true;
    }
    public boolean canSeekForward() {
        return true;
    }
}



//RedirectTracerTask.java
package app.test;

import java.net.HttpURLConnection;
import java.net.URL;

import android.net.Uri;
import android.os.AsyncTask;
import android.widget.VideoView;

public class RedirectTracerTask extends AsyncTask<Uri, Void, Uri> {

    private VideoView mVideo;
    private Uri initialUri;
    
    public RedirectTracerTask(VideoView video) {
        super();
        mVideo = video;
    }
    
    @Override
    protected Uri doInBackground(Uri... params) {
        initialUri = params[0];
        String redirected = null;
        try {
          URL url = new URL(initialUri.toString());
          HttpURLConnection connection = (HttpURLConnection)url.openConnection();
          redirected = connection.getHeaderField("Location");
          return Uri.parse(redirected);
        } catch (Exception e) {
          e.printStackTrace();
          return null;
        }  
    }
    
    @Override
    protected void onPostExecute(Uri result) {
        if(result != null) {
            mVideo.setVideoURI(result);
        } else {
            mVideo.setVideoURI(initialUri);
        }
    }
    
}



//VideoActivity.java
package app.test;

import java.io.File;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoActivity extends Activity {

    VideoView videoView;
    MediaController controller;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        videoView = new VideoView(this);
        videoView.setVideoURI( Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"MysticHigh.mp4")) );
        controller = new MediaController(this);
        videoView.setMediaController(controller);
        videoView.start();
        
        setContentView(videoView);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        videoView.stopPlayback();
    }
}



//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/root"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Now Playing..."
  />
  <ImageView
    android:id="@+id/coverImage"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="centerInside"
  />
</LinearLayout>

   
    
    
    
    
  








Related examples in the same category

1.Playing Back Sound Effects
2.Get Duration Of Sound