Android Tutorial - Media
- MediaScannerConnection
- Mp3
- SoundPool
- AudioRecord
- MediaRecorder
- MediaStore
- Sound
Using MediaScannerConnection
package app.test;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Test extends Activity implements MediaScannerConnectionClient {
private EditText editText = null;
private String filename = null;
private MediaScannerConnection conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.fileName);
}
public void startScan(View view) {
if(conn!=null) {
conn.disconnect();
}
filename = editText.getText().toString();
File fileCheck = new File(filename);
if(fileCheck.isFile()) {
conn = new MediaScannerConnection(this, this);
conn.connect();
}
else {
Toast.makeText(this,
"That file does not exist",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onMediaScannerConnected() {
conn.scanFile(filename, null);
}
@Override
public void onScanCompleted(String path, Uri uri) {
try {
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
conn.disconnect();
conn = null;
}
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<EditText android:id="@+id/fileName" android:hint="Enter new filename"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<Button android:id="@+id/scanBtn" android:text="Add file"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="startScan" />
</LinearLayout>
Play mp3 file within a service
package app.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
class Music extends Service {
private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
player = MediaPlayer.create(this, R.raw.mp3File);
player.start();
}
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.start);
button1.setOnClickListener(startIt);
Button button2 = (Button)findViewById(R.id.stop);
button2.setOnClickListener(stopIt);
}
private OnClickListener startIt = new OnClickListener()
{
public void onClick(View v)
{
startService(new Intent("app.test.Test.START_AUDIO_SERVICE"));
}
};
private OnClickListener stopIt = new OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent("app.test.Test.START_AUDIO_SERVICE"));
finish();
}
};
}
//main.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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Play"
/>
<Button
android:id="@+id/stop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop Play"
/>
</LinearLayout>
Async Mp3 Player Demo
package app.test;
import android.app.Activity;
import android.media.AsyncPlayer;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
public class MainActivity extends Activity {
private static final String TAG = "AsyncPlayerDemo";
private AsyncPlayer mAsync = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAsync = new AsyncPlayer(TAG);
mAsync.play(this, Uri.parse("file://" +
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_RINGTONES) +
"/my.mp3"),
false, AudioManager.STREAM_MUSIC);
}
@Override
protected void onPause() {
mAsync.stop();
super.onPause();
}
}
Play Mp3 file from a Url
package app.test;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
public class Test extends Activity
{
static final String AUDIO_PATH =
"http://yourHost/play.mp3";
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void doClick(View view) {
switch(view.getId()) {
case R.id.startPlayerBtn:
try {
playAudio(AUDIO_PATH);
playLocalAudio();
playLocalAudio_UsingDescriptor();
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.pausePlayerBtn:
if(mediaPlayer != null && mediaPlayer.isPlaying()) {
playbackPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
}
break;
case R.id.restartPlayerBtn:
if(mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(playbackPosition);
mediaPlayer.start();
}
break;
case R.id.stopPlayerBtn:
if(mediaPlayer != null) {
mediaPlayer.stop();
playbackPosition = 0;
}
break;
}
}
private void playAudio(String url) throws Exception
{
killMediaPlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
}
private void playLocalAudio() throws Exception
{
mediaPlayer = MediaPlayer.create(this, R.raw.music_file);
mediaPlayer.start();
}
private void playLocalAudio_UsingDescriptor() throws Exception {
AssetFileDescriptor fileDesc = getResources().openRawResourceFd(
R.raw.music_file);
if (fileDesc != null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileDesc.getFileDescriptor(), fileDesc
.getStartOffset(), fileDesc.getLength());
fileDesc.close();
mediaPlayer.prepare();
mediaPlayer.start();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
killMediaPlayer();
}
private void killMediaPlayer() {
if(mediaPlayer!=null) {
try {
mediaPlayer.release();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
Load Mp3 file from local file system
package app.test;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
public class Test extends Activity
{
static final String AUDIO_PATH =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/music_file.mp3";
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void doClick(View view) {
switch(view.getId()) {
case R.id.startPlayerBtn:
try {
playAudio(AUDIO_PATH);
playLocalAudio();
playLocalAudio_UsingDescriptor();
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.pausePlayerBtn:
if(mediaPlayer != null && mediaPlayer.isPlaying()) {
playbackPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
}
break;
case R.id.restartPlayerBtn:
if(mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(playbackPosition);
mediaPlayer.start();
}
break;
case R.id.stopPlayerBtn:
if(mediaPlayer != null) {
mediaPlayer.stop();
playbackPosition = 0;
}
break;
}
}
private void playAudio(String url) throws Exception
{
killMediaPlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
}
private void playLocalAudio() throws Exception
{
mediaPlayer = MediaPlayer.create(this, R.raw.music_file);
mediaPlayer.start();
}
private void playLocalAudio_UsingDescriptor() throws Exception {
AssetFileDescriptor fileDesc = getResources().openRawResourceFd(
R.raw.music_file);
if (fileDesc != null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileDesc.getFileDescriptor(), fileDesc
.getStartOffset(), fileDesc.getLength());
fileDesc.close();
mediaPlayer.prepare();
mediaPlayer.start();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
killMediaPlayer();
}
private void killMediaPlayer() {
if(mediaPlayer!=null) {
try {
mediaPlayer.release();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
Sound Pool Demo
package app.test;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ToggleButton;
public class Test extends Activity implements SoundPool.OnLoadCompleteListener {
private static final int SRC_QUALITY = 0;
private static final int PRIORITY = 1;
private SoundPool soundPool = null;
private AudioManager aMgr;
private int s0;
private int s1;
private int s2;
private int s3;
private int s4;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onResume() {
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, SRC_QUALITY);
soundPool.setOnLoadCompleteListener(this);
aMgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
s0 = soundPool.load(this, R.raw.s0, PRIORITY);
s3 = soundPool.load(this, R.raw.s1, PRIORITY);
s4 = soundPool.load(this, R.raw.s2, PRIORITY);
s1 = soundPool.load(this, R.raw.s3, PRIORITY);
try {
AssetFileDescriptor afd = this.getAssets().openFd("dogbark.mp3");
s2 = soundPool.load(afd.getFileDescriptor(), 0, afd.getLength(), PRIORITY);
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
s2 = soundPool.load("/mnt/sdcard/dogbark.mp3", PRIORITY);
super.onResume();
}
public void doClick(View view) {
switch(view.getId()) {
case R.id.button:
if(((ToggleButton)view).isChecked()) {
soundPool.autoResume();
}
else {
soundPool.autoPause();
}
break;
}
}
@Override
protected void onPause() {
soundPool.release();
soundPool = null;
super.onPause();
}
@Override
public void onLoadComplete(SoundPool sPool, int sid, int status) {
final float currentVolume = ((float)aMgr.getStreamVolume(AudioManager.STREAM_MUSIC)) /
((float)aMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
if(status != 0)
return;
if(sid == s0) {
if(sPool.play(sid, currentVolume, currentVolume,
PRIORITY, -1, 1.0f) == 0)
Log.v("soundPool", "Failed to start sound");
} else if(sid == s3) {
queueSound(sid, 5000, currentVolume);
} else if(sid == s4) {
queueSound(sid, 6000, currentVolume);
} else if(sid == s1) {
queueSound(sid, 12000, currentVolume);
} else if(sid == s2) {
queueSound(sid, 7000, currentVolume);
}
}
private void queueSound(final int sid, final long delay, final float volume) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(soundPool == null) return;
if(soundPool.play(sid, volume, volume,
PRIORITY, 0, 1.0f) == 0)
Log.v("soundPool", "Failed to start sound (" + sid + ")");
queueSound(sid, delay, volume);
}}, delay);
}
}
Using AudioRecord
package app.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener {
RecordAudio recordTask;
PlayAudio playTask;
Button startRecordingButton, stopRecordingButton, startPlaybackButton,
stopPlaybackButton;
TextView statusText;
File recordingFile;
boolean isRecording = false,isPlaying = false;
int frequency = 11025,channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
statusText = (TextView) this.findViewById(R.id.StatusTextView);
startRecordingButton = (Button) this
.findViewById(R.id.StartRecordingButton);
stopRecordingButton = (Button) this
.findViewById(R.id.StopRecordingButton);
startPlaybackButton = (Button) this
.findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this
.findViewById(R.id.StopPlaybackButton);
startRecordingButton.setOnClickListener(this);
stopRecordingButton.setOnClickListener(this);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
stopRecordingButton.setEnabled(false);
startPlaybackButton.setEnabled(false);
stopPlaybackButton.setEnabled(false);
File path = new File(
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/com.apress.proandroidmedia.ch07.altaudiorecorder/files/");
path.mkdirs();
try {
recordingFile = File.createTempFile("recording", ".pcm", path);
} catch (IOException e) {
throw new RuntimeException("Couldn't create file on SD card", e);
}
}
public void onClick(View v) {
if (v == startRecordingButton) {
record();
} else if (v == stopRecordingButton) {
stopRecording();
} else if (v == startPlaybackButton) {
play();
} else if (v == stopPlaybackButton) {
stopPlaying();
}
}
public void play() {
startPlaybackButton.setEnabled(true);
playTask = new PlayAudio();
playTask.execute();
stopPlaybackButton.setEnabled(true);
}
public void stopPlaying() {
isPlaying = false;
stopPlaybackButton.setEnabled(false);
startPlaybackButton.setEnabled(true);
}
public void record() {
startRecordingButton.setEnabled(false);
stopRecordingButton.setEnabled(true);
startPlaybackButton.setEnabled(true);
recordTask = new RecordAudio();
recordTask.execute();
}
public void stopRecording() {
isRecording = false;
}
private class PlayAudio extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
isPlaying = true;
int bufferSize = AudioTrack.getMinBufferSize(frequency,channelConfiguration, audioEncoding);
short[] audiodata = new short[bufferSize / 4];
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(recordingFile)));
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC, frequency,
channelConfiguration, audioEncoding, bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
while (isPlaying && dis.available() > 0) {
int i = 0;
while (dis.available() > 0 && i < audiodata.length) {
audiodata[i] = dis.readShort();
i++;
}
audioTrack.write(audiodata, 0, audiodata.length);
}
dis.close();
startPlaybackButton.setEnabled(false);
stopPlaybackButton.setEnabled(true);
} catch (Throwable t) {
Log.e("AudioTrack", "Playback Failed");
}
return null;
}
}
private class RecordAudio extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
isRecording = true;
try {
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(
recordingFile)));
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[bufferSize];
audioRecord.startRecording();
int r = 0;
while (isRecording) {
int bufferReadResult = audioRecord.read(buffer, 0,
bufferSize);
for (int i = 0; i < bufferReadResult; i++) {
dos.writeShort(buffer[i]);
}
publishProgress(new Integer(r));
r++;
}
audioRecord.stop();
dos.close();
} catch (Throwable t) {
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
statusText.setText(progress[0].toString());
}
protected void onPostExecute(Void result) {
startRecordingButton.setEnabled(true);
stopRecordingButton.setEnabled(false);
startPlaybackButton.setEnabled(true);
}
}
}
//main.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"
>
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Status" android:id="@+id/StatusTextView"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Recording" android:id="@+id/StartRecordingButton"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop Recording" android:id="@+id/StopRecordingButton"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Playback" android:id="@+id/StartPlaybackButton"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop Playback" android:id="@+id/StopPlaybackButton"></Button>
</LinearLayout>
MediaRecorder Demo
//main.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/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Recording"
/>
<Button
android:id="@+id/stopButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop Recording"
android:enabled="false"
/>
</LinearLayout>
package com.examples.audioin;
import java.io.File;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
public class RecordActivity extends Activity {
private MediaRecorder recorder;
private Button start, stop;
File path;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.startButton);
start.setOnClickListener(startListener);
stop = (Button)findViewById(R.id.stopButton);
stop.setOnClickListener(stopListener);
recorder = new MediaRecorder();
path = new File(Environment.getExternalStorageDirectory(),"myRecording.3gp");
resetRecorder();
}
@Override
public void onDestroy() {
super.onDestroy();
recorder.release();
}
private void resetRecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(path.getAbsolutePath());
try {
recorder.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
private View.OnClickListener startListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
recorder.start();
start.setEnabled(false);
stop.setEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
};
private View.OnClickListener stopListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
recorder.stop();
resetRecorder();
start.setEnabled(true);
stop.setEnabled(false);
}
};
}
Using RecordAmplitude
package app.test;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener,
OnCompletionListener {
TextView statusTextView, amplitudeTextView;
Button startRecording, stopRecording, playRecording, finishButton;
MediaRecorder recorder;
MediaPlayer player;
File audioFile;
RecordAmplitude recordAmplitude;
boolean isRecording = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
statusTextView = (TextView) this.findViewById(R.id.StatusTextView);
statusTextView.setText("Ready");
amplitudeTextView = (TextView) this
.findViewById(R.id.AmplitudeTextView);
amplitudeTextView.setText("0");
stopRecording = (Button) this.findViewById(R.id.StopRecording);
startRecording = (Button) this.findViewById(R.id.StartRecording);
playRecording = (Button) this.findViewById(R.id.PlayRecording);
finishButton = (Button) this.findViewById(R.id.FinishButton);
startRecording.setOnClickListener(this);
stopRecording.setOnClickListener(this);
playRecording.setOnClickListener(this);
finishButton.setOnClickListener(this);
stopRecording.setEnabled(false);
playRecording.setEnabled(false);
}
public void onClick(View v) {
if (v == finishButton) {
finish();
} else if (v == stopRecording) {
isRecording = false;
recordAmplitude.cancel(true);
recorder.stop();
recorder.release();
player = new MediaPlayer();
player.setOnCompletionListener(this);
try {
player.setDataSource(audioFile.getAbsolutePath());
player.prepare();
} catch (Exception e) {
throw new RuntimeException(
"Exception in MediaPlayer.prepare", e);
}
statusTextView.setText("Ready to Play");
playRecording.setEnabled(true);
stopRecording.setEnabled(false);
startRecording.setEnabled(true);
} else if (v == startRecording) {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
File path = new File(
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/files/");
path.mkdirs();
try {
audioFile = File.createTempFile("recording", ".3gp", path);
recorder.setOutputFile(audioFile.getAbsolutePath());
recorder.prepare();
} catch (Exception e) {
throw new RuntimeException(
"IOException on MediaRecorder.prepare", e);
}
recorder.start();
isRecording = true;
recordAmplitude = new RecordAmplitude();
recordAmplitude.execute();
statusTextView.setText("Recording");
playRecording.setEnabled(false);
stopRecording.setEnabled(true);
startRecording.setEnabled(false);
} else if (v == playRecording) {
player.start();
statusTextView.setText("Playing");
playRecording.setEnabled(false);
stopRecording.setEnabled(false);
startRecording.setEnabled(false);
}
}
public void onCompletion(MediaPlayer mp) {
playRecording.setEnabled(true);
stopRecording.setEnabled(false);
startRecording.setEnabled(true);
statusTextView.setText("Ready");
}
private class RecordAmplitude extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
while (isRecording) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(recorder.getMaxAmplitude());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
amplitudeTextView.setText(progress[0].toString());
}
}
}
//main.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"
>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/StatusTextView" android:text="Status" android:textSize="35dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AmplitudeTextView" android:textSize="35dip" android:text="0"></TextView>
<Button android:text="Start Recording" android:id="@+id/StartRecording" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Stop Recording" android:id="@+id/StopRecording" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Play Recording" android:id="@+id/PlayRecording" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/FinishButton" android:text="Finish"></Button>
</LinearLayout>
base class for recording various media//package org.andlib.helpers;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Handler;
abstract class MediaRecorderBase implements OnErrorListener, OnInfoListener
{
public static final int DEFAULT_SAMPLING_RATE = 44100; //44.1khz
public static final int DEFAULT_ENCODING_BITRATE = 128 * 1024; //128kbps
public static final int DEFAULT_NUM_CHANNELS = 2; //stereo
public static final int DEFAULT_FRAME_RATE = 24; //24 fps
public static final int DEFAULT_MAX_DURATION = 0; //infinite
public static final int DEFAULT_MAX_FILESIZE = 0; //infinite
protected Camera camera = null;
protected MediaRecorder recorder = null;
protected String filepath = null;
protected boolean isRecording = false;
protected int recorderState = -1;
protected Handler handler = null;
protected MediaRecorderListener listener = null;
/**
* default constructor that does nothing
*
*/
public MediaRecorderBase()
{
//do nothing
}
/**
* initialize recorder object
*/
protected void initRecorder()
{
if(recorder != null)
{
recorder.release();
recorder = null;
// Logger.v("recorder released");
}
isRecording = false;
recorder = new MediaRecorder();
if(camera != null)
recorder.setCamera(camera);
recorder.setOnErrorListener(this);
recorder.setOnInfoListener(this);
initRecorderMore();
}
protected abstract void initRecorderMore();
/**
*
* @return
*/
synchronized public boolean isRecording()
{
return isRecording;
}
synchronized public void startRecording(String filepath, Camera camera)
{
this.camera = camera;
initRecorder();
try
{
this.filepath = filepath;
recorder.setOutputFile(filepath);
recorder.prepare();
recorder.start();
isRecording = true;
// Logger.v("recording started");
recorderState = MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN;
if(listener != null && handler != null)
{
handler.post(new Runnable(){
@Override
public void run()
{
listener.onStartRecording();
}});
}
}
catch(Exception e)
{
if(camera != null)
{
try
{
camera.reconnect();
}
catch(Exception ce)
{
// Logger.e(ce.toString());
}
}
recorderState = MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN;
if(listener != null && handler != null)
{
handler.post(new Runnable(){
@Override
public void run()
{
listener.onErrorRecording(recorderState);
}});
}
// Logger.e(e.toString());
isRecording = false;
}
}
/**
* stop recording
*/
synchronized public void stopRecording()
{
if(isRecording)
{
//Logger.v("stop recording");
recorder.stop();
isRecording = false;
}
if(recorder != null)
{
recorder.release();
recorder = null;
// Logger.v("recorder released");
}
if(camera != null)
{
try
{
camera.reconnect();
}
catch(Exception e)
{
// Logger.e(e.toString());
}
}
recorderState = MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN;
if(listener != null && handler != null)
{
handler.post(new Runnable(){
@Override
public void run()
{
listener.onStopRecording(recorderState);
}});
}
}
public void setListener(Handler handler, MediaRecorderListener listener)
{
this.handler = handler;
this.listener = listener;
}
public interface MediaRecorderListener
{
/**
* called when recording started
*/
public void onStartRecording();
public void onStopRecording(int what);
public void onErrorRecording(int what);
}
/* (non-Javadoc)
* @see android.media.MediaRecorder.OnInfoListener#onInfo(android.media.MediaRecorder, int, int)
*/
@Override
public void onInfo(MediaRecorder mr, int what, int extra)
{
recorderState = what;
switch(what)
{
case MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN:
if(listener != null && handler != null)
{
handler.post(new Runnable(){
@Override
public void run()
{
listener.onErrorRecording(recorderState);
}});
}
break;
case MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED:
case MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED:
if(listener != null && handler != null)
{
handler.post(new Runnable(){
@Override
public void run()
{
listener.onStopRecording(recorderState);
}});
}
break;
}
//release
isRecording = false;
mr.release();
mr = null;
}
/* (non-Javadoc)
* @see android.media.MediaRecorder.OnErrorListener#onError(android.media.MediaRecorder, int, int)
*/
@Override
public void onError(MediaRecorder mr, int what, int extra)
{
recorderState = what;
switch(what)
{
case MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN:
if(listener != null && handler != null)
{
handler.post(new Runnable(){
@Override
public void run()
{
listener.onErrorRecording(recorderState);
}});
}
break;
}
//release
isRecording = false;
mr.release();
mr = null;
}
}
List the MediaStore
package app.test;
import java.io.File;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Test extends ListActivity {
Cursor cursor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] columns = { android.provider.MediaStore.Audio.Albums._ID,
android.provider.MediaStore.Audio.Albums.ALBUM };
cursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
columns, null, null, null);
String[] displayFields = new String[] { MediaStore.Audio.Albums.ALBUM };
int[] displayViews = new int[] { android.R.id.text1 };
setListAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor, displayFields,
displayViews));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
if (cursor.moveToPosition(position)) {
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.MIME_TYPE, };
String where = android.provider.MediaStore.Audio.Media.ALBUM
+ "=?";
String whereVal[] = { cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Albums.ALBUM)) };
String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
cursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns,
where, whereVal, orderBy);
String[] displayFields = new String[] { MediaStore.Audio.Media.DISPLAY_NAME };
int[] displayViews = new int[] { android.R.id.text1 };
setListAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor,
displayFields, displayViews));
}
}
}
Get Media information
package app.test;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.provider.MediaStore;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.IS_NOTIFICATION };
Cursor cursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, null,
null, null);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int mimeTypeColumn = cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE);
if (cursor.moveToFirst()) {
String audioFilePath = cursor.getString(fileColumn);
String mimeType = cursor.getString(mimeTypeColumn);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File newFile = new File(audioFilePath);
intent.setDataAndType(Uri.fromFile(newFile), mimeType);
startActivity(intent);
}
}
}
delete query Track, write play list
//package com.andrewchatham.pony;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
// Large parts of this file are cribbed from MusicUtil.java in the android music player.
public class MediaUtil {
public static final String TAG = "MediaUtil";
public static void deleteTrack(Context context, String localPath) {
Uri uri = MediaStore.Audio.Media.getContentUriForPath(localPath);
context.getContentResolver().delete(uri, null, null);
}
public static Cursor query(Context context, Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder, int limit) {
try {
ContentResolver resolver = context.getContentResolver();
if (resolver == null) {
return null;
}
if (limit > 0) {
uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
}
return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (UnsupportedOperationException ex) {
return null;
}
}
public static Cursor query(Context context, Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
return query(context, uri, projection, selection, selectionArgs, sortOrder, 0);
}
private static int intFromCursor(Cursor c) {
int id = -1;
if (c != null) {
c.moveToFirst();
if (!c.isAfterLast()) {
id = c.getInt(0);
}
}
c.close();
return id;
}
public static int idForplaylist(Context context, String name) {
Cursor c = query(context, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Playlists._ID },
MediaStore.Audio.Playlists.NAME + "=?",
new String[] { name },
MediaStore.Audio.Playlists.NAME);
return intFromCursor(c);
}
public static int idFortrack(Context context, String path) {
Cursor c = query(context, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media._ID },
MediaStore.Audio.Media.DATA + "=?",
new String[] { path },
MediaStore.Audio.Media.DATA);
return intFromCursor(c);
}
public static void writePlaylist(Context context, String playlistName, ArrayList<String> paths) {
ContentResolver resolver = context.getContentResolver();
int playlistId = idForplaylist(context, playlistName);
Uri uri;
if (playlistId == -1) {
ContentValues values = new ContentValues(1);
values.put(MediaStore.Audio.Playlists.NAME, playlistName);
uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values);
playlistId = idForplaylist(context, playlistName);
} else {
uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
}
Log.d(TAG, String.format("Writing playlist %s", uri));
// Delete everything from the old playlist
context.getContentResolver().delete(uri, null, null);
// Add all the new tracks to the playlist.
int size = paths.size();
ContentValues values [] = new ContentValues[size];
for (int k = 0; k < size; ++k) {
values[k] = new ContentValues();
values[k].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, k);
values[k].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, idFortrack(context, paths.get(k)));
}
resolver.bulkInsert(uri, values);
}
}
Playing Back Sound Effects
package app.test;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class Test extends Activity implements OnTouchListener {
SoundPool soundPool;
int explosionId = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setOnTouchListener(this);
setContentView(textView);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
try {
AssetManager assetManager = getAssets();
AssetFileDescriptor descriptor = assetManager.openFd("a.ogg");
explosionId = soundPool.load(descriptor, 1);
} catch (IOException e) {
textView.setText(e.getMessage());
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (explosionId != -1) {
soundPool.play(explosionId, 1, 1, 0, 0, 1);
}
}
return true;
}
}
Get Duration Of Sound//package org.andlib.helpers.sound;
import java.io.File;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
/**
* various utility functions for audio play
*
* @author meinside@gmail.com
* @since 10.10.29.
*
* last update 10.10.31.
*
*/
public class SoundUtility
{
/**
*
* @param context
* @param soundFile sound file object (can be one of: Integer(resource id), String(file path), or File)
* @return duration of given sound file in millis (0 if failed)
*/
public static long getDurationOfSound(Context context, Object soundFile)
{
int millis = 0;
MediaPlayer mp = new MediaPlayer();
try
{
Class<? extends Object> currentArgClass = soundFile.getClass();
if(currentArgClass == Integer.class)
{
AssetFileDescriptor afd = context.getResources().openRawResourceFd((Integer)soundFile);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
}
else if(currentArgClass == String.class)
{
mp.setDataSource((String)soundFile);
}
else if(currentArgClass == File.class)
{
mp.setDataSource(((File)soundFile).getAbsolutePath());
}
mp.prepare();
millis = mp.getDuration();
}
catch(Exception e)
{
// Logger.e(e.toString());
}
finally
{
mp.release();
mp = null;
}
return millis;
}
}
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>
Using MediaScannerConnection
package app.test; import java.io.File; import android.app.Activity; import android.content.Intent; import android.media.MediaScannerConnection; import android.media.MediaScannerConnection.MediaScannerConnectionClient; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class Test extends Activity implements MediaScannerConnectionClient { private EditText editText = null; private String filename = null; private MediaScannerConnection conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editText = (EditText)findViewById(R.id.fileName); } public void startScan(View view) { if(conn!=null) { conn.disconnect(); } filename = editText.getText().toString(); File fileCheck = new File(filename); if(fileCheck.isFile()) { conn = new MediaScannerConnection(this, this); conn.connect(); } else { Toast.makeText(this, "That file does not exist", Toast.LENGTH_SHORT).show(); } } @Override public void onMediaScannerConnected() { conn.scanFile(filename, null); } @Override public void onScanCompleted(String path, Uri uri) { try { if (uri != null) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); startActivity(intent); } } finally { conn.disconnect(); conn = null; } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/main.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/fileName" android:hint="Enter new filename" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/scanBtn" android:text="Add file" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startScan" /> </LinearLayout>
Play mp3 file within a service
package app.test; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; class Music extends Service { private MediaPlayer player; @Override public IBinder onBind(Intent intent) { return null; } public void onStart(Intent intent, int startId) { super.onStart(intent, startId); player = MediaPlayer.create(this, R.raw.mp3File); player.start(); } public void onDestroy() { super.onDestroy(); player.stop(); } } public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button1 = (Button)findViewById(R.id.start); button1.setOnClickListener(startIt); Button button2 = (Button)findViewById(R.id.stop); button2.setOnClickListener(stopIt); } private OnClickListener startIt = new OnClickListener() { public void onClick(View v) { startService(new Intent("app.test.Test.START_AUDIO_SERVICE")); } }; private OnClickListener stopIt = new OnClickListener() { public void onClick(View v) { stopService(new Intent("app.test.Test.START_AUDIO_SERVICE")); finish(); } }; } //main.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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/start" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start Play" /> <Button android:id="@+id/stop" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Stop Play" /> </LinearLayout>
Async Mp3 Player Demo
package app.test; import android.app.Activity; import android.media.AsyncPlayer; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Environment; public class MainActivity extends Activity { private static final String TAG = "AsyncPlayerDemo"; private AsyncPlayer mAsync = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAsync = new AsyncPlayer(TAG); mAsync.play(this, Uri.parse("file://" + Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_RINGTONES) + "/my.mp3"), false, AudioManager.STREAM_MUSIC); } @Override protected void onPause() { mAsync.stop(); super.onPause(); } }
Play Mp3 file from a Url
package app.test; import android.app.Activity; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; public class Test extends Activity { static final String AUDIO_PATH = "http://yourHost/play.mp3"; private MediaPlayer mediaPlayer; private int playbackPosition=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void doClick(View view) { switch(view.getId()) { case R.id.startPlayerBtn: try { playAudio(AUDIO_PATH); playLocalAudio(); playLocalAudio_UsingDescriptor(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.pausePlayerBtn: if(mediaPlayer != null && mediaPlayer.isPlaying()) { playbackPosition = mediaPlayer.getCurrentPosition(); mediaPlayer.pause(); } break; case R.id.restartPlayerBtn: if(mediaPlayer != null && !mediaPlayer.isPlaying()) { mediaPlayer.seekTo(playbackPosition); mediaPlayer.start(); } break; case R.id.stopPlayerBtn: if(mediaPlayer != null) { mediaPlayer.stop(); playbackPosition = 0; } break; } } private void playAudio(String url) throws Exception { killMediaPlayer(); mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(url); mediaPlayer.prepare(); mediaPlayer.start(); } private void playLocalAudio() throws Exception { mediaPlayer = MediaPlayer.create(this, R.raw.music_file); mediaPlayer.start(); } private void playLocalAudio_UsingDescriptor() throws Exception { AssetFileDescriptor fileDesc = getResources().openRawResourceFd( R.raw.music_file); if (fileDesc != null) { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(fileDesc.getFileDescriptor(), fileDesc .getStartOffset(), fileDesc.getLength()); fileDesc.close(); mediaPlayer.prepare(); mediaPlayer.start(); } } @Override protected void onDestroy() { super.onDestroy(); killMediaPlayer(); } private void killMediaPlayer() { if(mediaPlayer!=null) { try { mediaPlayer.release(); } catch(Exception e) { e.printStackTrace(); } } } }
Load Mp3 file from local file system
package app.test; import android.app.Activity; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; public class Test extends Activity { static final String AUDIO_PATH =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/music_file.mp3"; private MediaPlayer mediaPlayer; private int playbackPosition=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void doClick(View view) { switch(view.getId()) { case R.id.startPlayerBtn: try { playAudio(AUDIO_PATH); playLocalAudio(); playLocalAudio_UsingDescriptor(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.pausePlayerBtn: if(mediaPlayer != null && mediaPlayer.isPlaying()) { playbackPosition = mediaPlayer.getCurrentPosition(); mediaPlayer.pause(); } break; case R.id.restartPlayerBtn: if(mediaPlayer != null && !mediaPlayer.isPlaying()) { mediaPlayer.seekTo(playbackPosition); mediaPlayer.start(); } break; case R.id.stopPlayerBtn: if(mediaPlayer != null) { mediaPlayer.stop(); playbackPosition = 0; } break; } } private void playAudio(String url) throws Exception { killMediaPlayer(); mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(url); mediaPlayer.prepare(); mediaPlayer.start(); } private void playLocalAudio() throws Exception { mediaPlayer = MediaPlayer.create(this, R.raw.music_file); mediaPlayer.start(); } private void playLocalAudio_UsingDescriptor() throws Exception { AssetFileDescriptor fileDesc = getResources().openRawResourceFd( R.raw.music_file); if (fileDesc != null) { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(fileDesc.getFileDescriptor(), fileDesc .getStartOffset(), fileDesc.getLength()); fileDesc.close(); mediaPlayer.prepare(); mediaPlayer.start(); } } @Override protected void onDestroy() { super.onDestroy(); killMediaPlayer(); } private void killMediaPlayer() { if(mediaPlayer!=null) { try { mediaPlayer.release(); } catch(Exception e) { e.printStackTrace(); } } } }
Sound Pool Demo
package app.test; import java.io.IOException; import android.app.Activity; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.ToggleButton; public class Test extends Activity implements SoundPool.OnLoadCompleteListener { private static final int SRC_QUALITY = 0; private static final int PRIORITY = 1; private SoundPool soundPool = null; private AudioManager aMgr; private int s0; private int s1; private int s2; private int s3; private int s4; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onResume() { soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, SRC_QUALITY); soundPool.setOnLoadCompleteListener(this); aMgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE); s0 = soundPool.load(this, R.raw.s0, PRIORITY); s3 = soundPool.load(this, R.raw.s1, PRIORITY); s4 = soundPool.load(this, R.raw.s2, PRIORITY); s1 = soundPool.load(this, R.raw.s3, PRIORITY); try { AssetFileDescriptor afd = this.getAssets().openFd("dogbark.mp3"); s2 = soundPool.load(afd.getFileDescriptor(), 0, afd.getLength(), PRIORITY); afd.close(); } catch (IOException e) { e.printStackTrace(); } s2 = soundPool.load("/mnt/sdcard/dogbark.mp3", PRIORITY); super.onResume(); } public void doClick(View view) { switch(view.getId()) { case R.id.button: if(((ToggleButton)view).isChecked()) { soundPool.autoResume(); } else { soundPool.autoPause(); } break; } } @Override protected void onPause() { soundPool.release(); soundPool = null; super.onPause(); } @Override public void onLoadComplete(SoundPool sPool, int sid, int status) { final float currentVolume = ((float)aMgr.getStreamVolume(AudioManager.STREAM_MUSIC)) / ((float)aMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC)); if(status != 0) return; if(sid == s0) { if(sPool.play(sid, currentVolume, currentVolume, PRIORITY, -1, 1.0f) == 0) Log.v("soundPool", "Failed to start sound"); } else if(sid == s3) { queueSound(sid, 5000, currentVolume); } else if(sid == s4) { queueSound(sid, 6000, currentVolume); } else if(sid == s1) { queueSound(sid, 12000, currentVolume); } else if(sid == s2) { queueSound(sid, 7000, currentVolume); } } private void queueSound(final int sid, final long delay, final float volume) { new Handler().postDelayed(new Runnable() { @Override public void run() { if(soundPool == null) return; if(soundPool.play(sid, volume, volume, PRIORITY, 0, 1.0f) == 0) Log.v("soundPool", "Failed to start sound (" + sid + ")"); queueSound(sid, delay, volume); }}, delay); } }
Using AudioRecord
package app.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class Test extends Activity implements OnClickListener { RecordAudio recordTask; PlayAudio playTask; Button startRecordingButton, stopRecordingButton, startPlaybackButton, stopPlaybackButton; TextView statusText; File recordingFile; boolean isRecording = false,isPlaying = false; int frequency = 11025,channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioEncoding = AudioFormat.ENCODING_PCM_16BIT; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); statusText = (TextView) this.findViewById(R.id.StatusTextView); startRecordingButton = (Button) this .findViewById(R.id.StartRecordingButton); stopRecordingButton = (Button) this .findViewById(R.id.StopRecordingButton); startPlaybackButton = (Button) this .findViewById(R.id.StartPlaybackButton); stopPlaybackButton = (Button) this .findViewById(R.id.StopPlaybackButton); startRecordingButton.setOnClickListener(this); stopRecordingButton.setOnClickListener(this); startPlaybackButton.setOnClickListener(this); stopPlaybackButton.setOnClickListener(this); stopRecordingButton.setEnabled(false); startPlaybackButton.setEnabled(false); stopPlaybackButton.setEnabled(false); File path = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.apress.proandroidmedia.ch07.altaudiorecorder/files/"); path.mkdirs(); try { recordingFile = File.createTempFile("recording", ".pcm", path); } catch (IOException e) { throw new RuntimeException("Couldn't create file on SD card", e); } } public void onClick(View v) { if (v == startRecordingButton) { record(); } else if (v == stopRecordingButton) { stopRecording(); } else if (v == startPlaybackButton) { play(); } else if (v == stopPlaybackButton) { stopPlaying(); } } public void play() { startPlaybackButton.setEnabled(true); playTask = new PlayAudio(); playTask.execute(); stopPlaybackButton.setEnabled(true); } public void stopPlaying() { isPlaying = false; stopPlaybackButton.setEnabled(false); startPlaybackButton.setEnabled(true); } public void record() { startRecordingButton.setEnabled(false); stopRecordingButton.setEnabled(true); startPlaybackButton.setEnabled(true); recordTask = new RecordAudio(); recordTask.execute(); } public void stopRecording() { isRecording = false; } private class PlayAudio extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { isPlaying = true; int bufferSize = AudioTrack.getMinBufferSize(frequency,channelConfiguration, audioEncoding); short[] audiodata = new short[bufferSize / 4]; try { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(recordingFile))); AudioTrack audioTrack = new AudioTrack( AudioManager.STREAM_MUSIC, frequency, channelConfiguration, audioEncoding, bufferSize, AudioTrack.MODE_STREAM); audioTrack.play(); while (isPlaying && dis.available() > 0) { int i = 0; while (dis.available() > 0 && i < audiodata.length) { audiodata[i] = dis.readShort(); i++; } audioTrack.write(audiodata, 0, audiodata.length); } dis.close(); startPlaybackButton.setEnabled(false); stopPlaybackButton.setEnabled(true); } catch (Throwable t) { Log.e("AudioTrack", "Playback Failed"); } return null; } } private class RecordAudio extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { isRecording = true; try { DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream( recordingFile))); int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding); AudioRecord audioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize); short[] buffer = new short[bufferSize]; audioRecord.startRecording(); int r = 0; while (isRecording) { int bufferReadResult = audioRecord.read(buffer, 0, bufferSize); for (int i = 0; i < bufferReadResult; i++) { dos.writeShort(buffer[i]); } publishProgress(new Integer(r)); r++; } audioRecord.stop(); dos.close(); } catch (Throwable t) { Log.e("AudioRecord", "Recording Failed"); } return null; } protected void onProgressUpdate(Integer... progress) { statusText.setText(progress[0].toString()); } protected void onPostExecute(Void result) { startRecordingButton.setEnabled(true); stopRecordingButton.setEnabled(false); startPlaybackButton.setEnabled(true); } } } //main.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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Status" android:id="@+id/StatusTextView"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Recording" android:id="@+id/StartRecordingButton"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop Recording" android:id="@+id/StopRecordingButton"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Playback" android:id="@+id/StartPlaybackButton"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop Playback" android:id="@+id/StopPlaybackButton"></Button> </LinearLayout>
MediaRecorder Demo
//main.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/startButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start Recording" /> <Button android:id="@+id/stopButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Stop Recording" android:enabled="false" /> </LinearLayout> package com.examples.audioin; import java.io.File; import android.app.Activity; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; public class RecordActivity extends Activity { private MediaRecorder recorder; private Button start, stop; File path; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); start = (Button)findViewById(R.id.startButton); start.setOnClickListener(startListener); stop = (Button)findViewById(R.id.stopButton); stop.setOnClickListener(stopListener); recorder = new MediaRecorder(); path = new File(Environment.getExternalStorageDirectory(),"myRecording.3gp"); resetRecorder(); } @Override public void onDestroy() { super.onDestroy(); recorder.release(); } private void resetRecorder() { recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); recorder.setOutputFile(path.getAbsolutePath()); try { recorder.prepare(); } catch (Exception e) { e.printStackTrace(); } } private View.OnClickListener startListener = new View.OnClickListener() { @Override public void onClick(View v) { try { recorder.start(); start.setEnabled(false); stop.setEnabled(true); } catch (Exception e) { e.printStackTrace(); } } }; private View.OnClickListener stopListener = new View.OnClickListener() { @Override public void onClick(View v) { recorder.stop(); resetRecorder(); start.setEnabled(true); stop.setEnabled(false); } }; }
Using RecordAmplitude
package app.test; import java.io.File; import java.io.IOException; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.media.MediaPlayer.OnCompletionListener; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class Test extends Activity implements OnClickListener, OnCompletionListener { TextView statusTextView, amplitudeTextView; Button startRecording, stopRecording, playRecording, finishButton; MediaRecorder recorder; MediaPlayer player; File audioFile; RecordAmplitude recordAmplitude; boolean isRecording = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); statusTextView = (TextView) this.findViewById(R.id.StatusTextView); statusTextView.setText("Ready"); amplitudeTextView = (TextView) this .findViewById(R.id.AmplitudeTextView); amplitudeTextView.setText("0"); stopRecording = (Button) this.findViewById(R.id.StopRecording); startRecording = (Button) this.findViewById(R.id.StartRecording); playRecording = (Button) this.findViewById(R.id.PlayRecording); finishButton = (Button) this.findViewById(R.id.FinishButton); startRecording.setOnClickListener(this); stopRecording.setOnClickListener(this); playRecording.setOnClickListener(this); finishButton.setOnClickListener(this); stopRecording.setEnabled(false); playRecording.setEnabled(false); } public void onClick(View v) { if (v == finishButton) { finish(); } else if (v == stopRecording) { isRecording = false; recordAmplitude.cancel(true); recorder.stop(); recorder.release(); player = new MediaPlayer(); player.setOnCompletionListener(this); try { player.setDataSource(audioFile.getAbsolutePath()); player.prepare(); } catch (Exception e) { throw new RuntimeException( "Exception in MediaPlayer.prepare", e); } statusTextView.setText("Ready to Play"); playRecording.setEnabled(true); stopRecording.setEnabled(false); startRecording.setEnabled(true); } else if (v == startRecording) { recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); File path = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/files/"); path.mkdirs(); try { audioFile = File.createTempFile("recording", ".3gp", path); recorder.setOutputFile(audioFile.getAbsolutePath()); recorder.prepare(); } catch (Exception e) { throw new RuntimeException( "IOException on MediaRecorder.prepare", e); } recorder.start(); isRecording = true; recordAmplitude = new RecordAmplitude(); recordAmplitude.execute(); statusTextView.setText("Recording"); playRecording.setEnabled(false); stopRecording.setEnabled(true); startRecording.setEnabled(false); } else if (v == playRecording) { player.start(); statusTextView.setText("Playing"); playRecording.setEnabled(false); stopRecording.setEnabled(false); startRecording.setEnabled(false); } } public void onCompletion(MediaPlayer mp) { playRecording.setEnabled(true); stopRecording.setEnabled(false); startRecording.setEnabled(true); statusTextView.setText("Ready"); } private class RecordAmplitude extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { while (isRecording) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } publishProgress(recorder.getMaxAmplitude()); } return null; } protected void onProgressUpdate(Integer... progress) { amplitudeTextView.setText(progress[0].toString()); } } } //main.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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/StatusTextView" android:text="Status" android:textSize="35dip"></TextView> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AmplitudeTextView" android:textSize="35dip" android:text="0"></TextView> <Button android:text="Start Recording" android:id="@+id/StartRecording" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="Stop Recording" android:id="@+id/StopRecording" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="Play Recording" android:id="@+id/PlayRecording" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/FinishButton" android:text="Finish"></Button> </LinearLayout>
//package org.andlib.helpers; import android.hardware.Camera; import android.media.MediaRecorder; import android.media.MediaRecorder.OnErrorListener; import android.media.MediaRecorder.OnInfoListener; import android.os.Handler; abstract class MediaRecorderBase implements OnErrorListener, OnInfoListener { public static final int DEFAULT_SAMPLING_RATE = 44100; //44.1khz public static final int DEFAULT_ENCODING_BITRATE = 128 * 1024; //128kbps public static final int DEFAULT_NUM_CHANNELS = 2; //stereo public static final int DEFAULT_FRAME_RATE = 24; //24 fps public static final int DEFAULT_MAX_DURATION = 0; //infinite public static final int DEFAULT_MAX_FILESIZE = 0; //infinite protected Camera camera = null; protected MediaRecorder recorder = null; protected String filepath = null; protected boolean isRecording = false; protected int recorderState = -1; protected Handler handler = null; protected MediaRecorderListener listener = null; /** * default constructor that does nothing * */ public MediaRecorderBase() { //do nothing } /** * initialize recorder object */ protected void initRecorder() { if(recorder != null) { recorder.release(); recorder = null; // Logger.v("recorder released"); } isRecording = false; recorder = new MediaRecorder(); if(camera != null) recorder.setCamera(camera); recorder.setOnErrorListener(this); recorder.setOnInfoListener(this); initRecorderMore(); } protected abstract void initRecorderMore(); /** * * @return */ synchronized public boolean isRecording() { return isRecording; } synchronized public void startRecording(String filepath, Camera camera) { this.camera = camera; initRecorder(); try { this.filepath = filepath; recorder.setOutputFile(filepath); recorder.prepare(); recorder.start(); isRecording = true; // Logger.v("recording started"); recorderState = MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN; if(listener != null && handler != null) { handler.post(new Runnable(){ @Override public void run() { listener.onStartRecording(); }}); } } catch(Exception e) { if(camera != null) { try { camera.reconnect(); } catch(Exception ce) { // Logger.e(ce.toString()); } } recorderState = MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN; if(listener != null && handler != null) { handler.post(new Runnable(){ @Override public void run() { listener.onErrorRecording(recorderState); }}); } // Logger.e(e.toString()); isRecording = false; } } /** * stop recording */ synchronized public void stopRecording() { if(isRecording) { //Logger.v("stop recording"); recorder.stop(); isRecording = false; } if(recorder != null) { recorder.release(); recorder = null; // Logger.v("recorder released"); } if(camera != null) { try { camera.reconnect(); } catch(Exception e) { // Logger.e(e.toString()); } } recorderState = MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN; if(listener != null && handler != null) { handler.post(new Runnable(){ @Override public void run() { listener.onStopRecording(recorderState); }}); } } public void setListener(Handler handler, MediaRecorderListener listener) { this.handler = handler; this.listener = listener; } public interface MediaRecorderListener { /** * called when recording started */ public void onStartRecording(); public void onStopRecording(int what); public void onErrorRecording(int what); } /* (non-Javadoc) * @see android.media.MediaRecorder.OnInfoListener#onInfo(android.media.MediaRecorder, int, int) */ @Override public void onInfo(MediaRecorder mr, int what, int extra) { recorderState = what; switch(what) { case MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN: if(listener != null && handler != null) { handler.post(new Runnable(){ @Override public void run() { listener.onErrorRecording(recorderState); }}); } break; case MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: case MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED: if(listener != null && handler != null) { handler.post(new Runnable(){ @Override public void run() { listener.onStopRecording(recorderState); }}); } break; } //release isRecording = false; mr.release(); mr = null; } /* (non-Javadoc) * @see android.media.MediaRecorder.OnErrorListener#onError(android.media.MediaRecorder, int, int) */ @Override public void onError(MediaRecorder mr, int what, int extra) { recorderState = what; switch(what) { case MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN: if(listener != null && handler != null) { handler.post(new Runnable(){ @Override public void run() { listener.onErrorRecording(recorderState); }}); } break; } //release isRecording = false; mr.release(); mr = null; } }
List the MediaStore
package app.test; import java.io.File; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class Test extends ListActivity { Cursor cursor; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] columns = { android.provider.MediaStore.Audio.Albums._ID, android.provider.MediaStore.Audio.Albums.ALBUM }; cursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, columns, null, null, null); String[] displayFields = new String[] { MediaStore.Audio.Albums.ALBUM }; int[] displayViews = new int[] { android.R.id.text1 }; setListAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, displayFields, displayViews)); } protected void onListItemClick(ListView l, View v, int position, long id) { if (cursor.moveToPosition(position)) { String[] columns = { MediaStore.Audio.Media.DATA, MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.MIME_TYPE, }; String where = android.provider.MediaStore.Audio.Media.ALBUM + "=?"; String whereVal[] = { cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Albums.ALBUM)) }; String orderBy = android.provider.MediaStore.Audio.Media.TITLE; cursor = managedQuery( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, where, whereVal, orderBy); String[] displayFields = new String[] { MediaStore.Audio.Media.DISPLAY_NAME }; int[] displayViews = new int[] { android.R.id.text1 }; setListAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, displayFields, displayViews)); } } }
Get Media information
package app.test; import java.io.File; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.provider.MediaStore; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] columns = { MediaStore.Audio.Media.DATA, MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.IS_RINGTONE, MediaStore.Audio.Media.IS_ALARM, MediaStore.Audio.Media.IS_MUSIC, MediaStore.Audio.Media.IS_NOTIFICATION }; Cursor cursor = managedQuery( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, null, null, null); int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA); int mimeTypeColumn = cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE); if (cursor.moveToFirst()) { String audioFilePath = cursor.getString(fileColumn); String mimeType = cursor.getString(mimeTypeColumn); Intent intent = new Intent(android.content.Intent.ACTION_VIEW); File newFile = new File(audioFilePath); intent.setDataAndType(Uri.fromFile(newFile), mimeType); startActivity(intent); } } }
delete query Track, write play list
//package com.andrewchatham.pony; import java.util.ArrayList; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; // Large parts of this file are cribbed from MusicUtil.java in the android music player. public class MediaUtil { public static final String TAG = "MediaUtil"; public static void deleteTrack(Context context, String localPath) { Uri uri = MediaStore.Audio.Media.getContentUriForPath(localPath); context.getContentResolver().delete(uri, null, null); } public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, int limit) { try { ContentResolver resolver = context.getContentResolver(); if (resolver == null) { return null; } if (limit > 0) { uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build(); } return resolver.query(uri, projection, selection, selectionArgs, sortOrder); } catch (UnsupportedOperationException ex) { return null; } } public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return query(context, uri, projection, selection, selectionArgs, sortOrder, 0); } private static int intFromCursor(Cursor c) { int id = -1; if (c != null) { c.moveToFirst(); if (!c.isAfterLast()) { id = c.getInt(0); } } c.close(); return id; } public static int idForplaylist(Context context, String name) { Cursor c = query(context, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Playlists._ID }, MediaStore.Audio.Playlists.NAME + "=?", new String[] { name }, MediaStore.Audio.Playlists.NAME); return intFromCursor(c); } public static int idFortrack(Context context, String path) { Cursor c = query(context, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Media._ID }, MediaStore.Audio.Media.DATA + "=?", new String[] { path }, MediaStore.Audio.Media.DATA); return intFromCursor(c); } public static void writePlaylist(Context context, String playlistName, ArrayList<String> paths) { ContentResolver resolver = context.getContentResolver(); int playlistId = idForplaylist(context, playlistName); Uri uri; if (playlistId == -1) { ContentValues values = new ContentValues(1); values.put(MediaStore.Audio.Playlists.NAME, playlistName); uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values); playlistId = idForplaylist(context, playlistName); } else { uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId); } Log.d(TAG, String.format("Writing playlist %s", uri)); // Delete everything from the old playlist context.getContentResolver().delete(uri, null, null); // Add all the new tracks to the playlist. int size = paths.size(); ContentValues values [] = new ContentValues[size]; for (int k = 0; k < size; ++k) { values[k] = new ContentValues(); values[k].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, k); values[k].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, idFortrack(context, paths.get(k))); } resolver.bulkInsert(uri, values); } }
Playing Back Sound Effects
package app.test; import java.io.IOException; import android.app.Activity; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.TextView; public class Test extends Activity implements OnTouchListener { SoundPool soundPool; int explosionId = -1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textView = new TextView(this); textView.setOnTouchListener(this); setContentView(textView); setVolumeControlStream(AudioManager.STREAM_MUSIC); soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0); try { AssetManager assetManager = getAssets(); AssetFileDescriptor descriptor = assetManager.openFd("a.ogg"); explosionId = soundPool.load(descriptor, 1); } catch (IOException e) { textView.setText(e.getMessage()); } } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (explosionId != -1) { soundPool.play(explosionId, 1, 1, 0, 0, 1); } } return true; } }
//package org.andlib.helpers.sound; import java.io.File; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; /** * various utility functions for audio play * * @author meinside@gmail.com * @since 10.10.29. * * last update 10.10.31. * */ public class SoundUtility { /** * * @param context * @param soundFile sound file object (can be one of: Integer(resource id), String(file path), or File) * @return duration of given sound file in millis (0 if failed) */ public static long getDurationOfSound(Context context, Object soundFile) { int millis = 0; MediaPlayer mp = new MediaPlayer(); try { Class<? extends Object> currentArgClass = soundFile.getClass(); if(currentArgClass == Integer.class) { AssetFileDescriptor afd = context.getResources().openRawResourceFd((Integer)soundFile); mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } else if(currentArgClass == String.class) { mp.setDataSource((String)soundFile); } else if(currentArgClass == File.class) { mp.setDataSource(((File)soundFile).getAbsolutePath()); } mp.prepare(); millis = mp.getDuration(); } catch(Exception e) { // Logger.e(e.toString()); } finally { mp.release(); mp = null; } return millis; } }
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>