I am new to android. I want to play a audio file when my mobile get shaking. I know the acceleration code. But when I wrote mediaplayer code I didn't get any output from my device.
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
MediaPlayer mPlayer1 = MediaPlayer.create(null, R.raw.hello);
try {
mPlayer1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer1.start();
}
}
You should provide a Context while creating a MediaPlayer. E.g.
MediaPlayer.create(getApplicationContext(), R.raw.hello);
Also, it would advisable to create a MediaPlayer beforehand.
Modify ur code like this. Hope this works.
MediaPlayer mPlayer1 = MediaPlayer.create(null, R.raw.hello);
into
MediaPlayer mPlayer1 = MediaPlayer.create(getApplicationContext(), R.raw.hello);
Use below class for shake listener,
import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener{
private MyShakeListener mOnShakeListener = null;
private SensorManager mSensorManager;
private double mTotalForcePrev;
private double mForceThreshHold = 1.5f;
private List<Sensor> mSensors;
private Sensor mAccelerationSensor;
public ShakeListener(SensorManager sm){
mSensorManager = sm;
mSensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(mSensors.size() > 0) {
mAccelerationSensor = mSensors.get(0);
mSensorManager.registerListener(this, mAccelerationSensor, SensorManager.SENSOR_DELAY_GAME);
}
}
public void setForceThreshHold(double threshhold){
mForceThreshHold = threshhold;
}
public double getForceThreshHold(){
return mForceThreshHold;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
double totalForce = 0.0f;
totalForce += Math.pow(event.values[0]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(event.values[1]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(event.values[2]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce = Math.sqrt(totalForce);
if((totalForce < mForceThreshHold) && (mTotalForcePrev > mForceThreshHold)) {
OnShake();
}
mTotalForcePrev = totalForce;
}
public void setOnShakeListener(MyShakeListener listener)
{
mOnShakeListener = listener;
}
private void OnShake()
{
if(mOnShakeListener!=null)
{
mOnShakeListener.onShake();
}
}
}
public interface MyShakeListener {
public abstract void onShake();
}
and add the lisener class on your main class like this,
public class MainActivity extends Activity
{
MediaPlayer defaultPlayer;
#Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.playerscree);
ShakeListener myShake = new ShakeListener((SensorManager)getSystemService(Context.SENSOR_SERVICE));
myShake.setForceThreshHold(1.9);
myShake.setOnShakeListener(new MyShakeListener()
{
#Override
public void onShake()
{
// do ur work here...
defaultPlayer= MediaPlayer.create(getApplicationContext(), R.raw.music);
defaultPlayer.start();
}
});
}
Related
Requirement is to play a chime sound an phrase after that using Android Text to Speech.
for (final Integer orderId : voiceoverIds) {
alertChimePlayer = MediaPlayer.create(getApplicationContext(), R.raw.orderalert);
alertChimePlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
String orderSpeechText = "Number " + orderId;
textToSpeech.speak(orderSpeechText, TextToSpeech.QUEUE_ADD, null, "ORDER_NO_" + orderId);
textToSpeech.playSilentUtterance(2000, TextToSpeech.QUEUE_ADD, "PAUSE_NO_" + orderId);
System.out.println(">>>>>>>>>>>>>>>>>>> orderSpeechText : " + orderSpeechText);
}
});
alertChimePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
alertChimePlayer.start();
}
});
}
But this only works one time. How to handle this properly?
Good question. Stayed up all night on this. The problem is that in the loop, those chimes just get rapidly sent to the media player all at the same time. Media Player cant really handle that properly.
Here is my solution. I am using SoundPool to play the chime because it is better at playing short sounds in repetition.
I am also using a timer thread to trigger the "Chime + spoken text-to-speech (tts)" sequences. The tts onUtteranceProgressListener is used to play the tts after the chime sound.
Here is the tested code. What you will hear is:
chime "number 1" (3 second delay)
chime "number 2" (3 second delay)
... continues until terminated
import android.app.Activity;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import java.util.Locale;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
AudioAttributes aa;
SoundPool sp;
private TextToSpeech tts;
int MAX_STREAMS = 5;
int REPEAT = 0;
int DELAY = 3000;
int orderId = 0;
// Clock thread
Thread m_clockThread;
boolean m_bClockThreadStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("TTS", "Starting...");
// Set up the sound pool sound
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build();
sp = new SoundPool.Builder()
.setMaxStreams(8)
.setAudioAttributes(aa)
.build();
// Start the tts
tts = new TextToSpeech(MainActivity.this,MainActivity.this);
tts.setLanguage(Locale.US);
}
#Override
public void onInit(int status) {
Log.e("TTS", "Enter onInit...");
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
Log.e("TTS", "onInit Success");
// create and run clock thread
createAndRunClockThread(this);
}
} else {
Log.e("TTS", "onInit Fail");
}
}
public void createAndRunClockThread(final Activity act) {
m_bClockThreadStop=false;
m_clockThread = new Thread(new Runnable() {
public void run() {
while(!m_bClockThreadStop) {
try {
act.runOnUiThread(new Runnable() {
public void run() {
playChime();
}
});
Thread.sleep(DELAY);
}
catch(InterruptedException e) {
Log.e("TTS", "ClockThread fail");
}
}
}
});
m_clockThread.start();
}
private void playChime() {
Log.e("TTS", "Entering startChimes...");
sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(final SoundPool soundPool, final int soundId, int status) {
final int priority = 0;
final int repeat = 0;
final float rate = 1.f; // Frequency Rate can be from .5 to 2.0
// Set volume
AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
final float volume = streamVolumeCurrent / streamVolumeMax;
// Play a chime followed by the tts
tts.speak("Number " + orderId, TextToSpeech.QUEUE_ADD, null, "ID" + orderId);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
// Speaking started.
sp.play(soundId, volume, volume, priority, repeat, rate);
}
#Override
public void onDone(String utteranceId) {
// Speaking stopped.
orderId = orderId + 1;
}
#Override
public void onError(String utteranceId) {
// There was an error.
}
});
}
});
sp.load(this, R.raw.beep, 1);
}
}
Thanks for the answer #Mark W. But I was thinking of solution that doesn't involve explicit delays/sleeps.
So I was implementing this Service Class.
public class OrderNoticeService extends Service implements TextToSpeech.OnInitListener {
private List<OrderSpeechAsyncTask> orderSpeechAsyncTasks = new ArrayList<>();
private TextToSpeech textToSpeech;
private Context context;
public void addToOrderNoticeQueue(int orderId) {
String orderSpeechText = String.format(getResources().getString(R.string.order_voice_over_default_text), Integer.toString(orderId));
orderSpeechAsyncTasks.add(new OrderSpeechAsyncTask(getApplicationContext(), R.raw.orderalert, orderSpeechText, textToSpeech, new AsyncTaskCallback() {
#Override
public void onTaskCompleted(Object response) {
}
}));
if (orderSpeechAsyncTasks.size() > 1) {
final OrderSpeechAsyncTask orderSpeechAsyncTask = orderSpeechAsyncTasks.get(orderSpeechAsyncTasks.size() - 1);
OrderSpeechAsyncTask orderSpeechAsyncTaskPrior = orderSpeechAsyncTasks.get(orderSpeechAsyncTasks.size() - 2);
orderSpeechAsyncTaskPrior.setAsyncTaskCallback(new AsyncTaskCallback() {
#Override
public void onTaskCompleted(Object response) {
try {
orderSpeechAsyncTask.execute();
System.out.println("Execution!");
} catch (Exception e) {
}
}
});
}
}
#Override
public void onCreate() {
textToSpeech = new TextToSpeech(this, this);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
return Service.START_STICKY;
}
private static final String TAG = "OrderNoticeService";
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "OrderNoticeService onBind");
return mBinder;
}
#Override
public void onDestroy() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
Log.i(TAG, "OrderNoticeService onDestroy");
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
OrderNoticeVoiceOverThread orderNoticeVoiceOverThread = new OrderNoticeVoiceOverThread(context, orderSpeechAsyncTasks);
orderNoticeVoiceOverThread.start();
} else {
System.out.println("Text To Speech not supported!");
}
}
private class OrderNoticeVoiceOverThread extends Thread {
private Context context;
private List<OrderSpeechAsyncTask> orderSpeechAsyncTasks;
private boolean anyTaskRunning = false;
public OrderNoticeVoiceOverThread(Context context, List<OrderSpeechAsyncTask> orderSpeechAsyncTasks) {
this.context = context;
this.orderSpeechAsyncTasks = orderSpeechAsyncTasks;
}
public void run() {
while (true) {
for (OrderSpeechAsyncTask orderSpeechAsyncTask : new ArrayList<OrderSpeechAsyncTask>(orderSpeechAsyncTasks)) {
if (orderSpeechAsyncTask != null && orderSpeechAsyncTask.getStatus().equals(AsyncTask.Status.RUNNING)) {
anyTaskRunning = true;
break;
}
}
if (!anyTaskRunning) {
for (OrderSpeechAsyncTask orderSpeechAsyncTask : new ArrayList<OrderSpeechAsyncTask>(orderSpeechAsyncTasks)) {
if (orderSpeechAsyncTask != null && orderSpeechAsyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
orderSpeechAsyncTask.execute();
anyTaskRunning = false;
break;
}
}
}
}
}
}
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public OrderNoticeService getService() {
return OrderNoticeService.this;
}
}
}
And the OrderSpeechAsyncTask as follows.
public class OrderSpeechAsyncTask extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = OrderSpeechAsyncTask.class.getSimpleName();
private MediaPlayer mediaPlayer;
private int soundId;
private Context context;
private String orderSpeechText;
private AsyncTaskCallback asyncTaskCallback;
private TextToSpeech textToSpeech;
public OrderSpeechAsyncTask(final Context context, int soundId, String orderSpeechText, TextToSpeech textToSpeech, AsyncTaskCallback asyncTaskCallback) {
this.context = context;
this.soundId = soundId;
this.orderSpeechText = orderSpeechText;
this.textToSpeech = textToSpeech;
this.asyncTaskCallback = asyncTaskCallback;
}
public AsyncTaskCallback getAsyncTaskCallback() {
return asyncTaskCallback;
}
public void setAsyncTaskCallback(AsyncTaskCallback asyncTaskCallback) {
this.asyncTaskCallback = asyncTaskCallback;
}
#Override
protected Void doInBackground(Void... params) {
mediaPlayer = MediaPlayer.create(context, soundId);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
textToSpeech.speak(orderSpeechText, TextToSpeech.QUEUE_ADD, null, "ORDER_NO_" + orderSpeechText);
textToSpeech.playSilentUtterance(2000, TextToSpeech.QUEUE_ADD, "PAUSE_NO_" + orderSpeechText);
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
asyncTaskCallback.onTaskCompleted(null);
}
#Override
public void onError(String utteranceId) {
}
});
}
});
mediaPlayer.start();
return null;
}
}
This so far handles the following;
Playing the sound and the text in the list
Adding an item to the queue whilst the existing list is still being read
To do;
This doesn't handle any new item that gets added to the list once the existing items are done being read.
I have a image button and video url. I want that video play when user onClick image button.I want that video played on same activity if that video stream is over then I have to return to same activity.
VideoView videoView;
ImageView btnWatchVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotions_feed);
btnWatchVideo = (ImageView) findViewById(R.id.btnWatchVideo);
videoView = (VideoView) findViewById(R.id.ltVideoUrl);
String path1 = "https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v";
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri uri = Uri.parse(path1);
videoView.setMediaController(mc);
videoView.setVideoURI(uri);
btnWatchVideo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
videoView.start();
}
});
This code is not working. Can any one suggest me how to do that.
Try using these two onCreate methods for the two Activities.
Video Vewing Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
videoView = (VideoView) findViewById(R.id.ltVideoUrl);
String path1 = "https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v";
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri uri = Uri.parse(path1);
videoView.setMediaController(mc);
videoView.setVideoURI(uri);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videoView.start();
}
});}
Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnWatchVideo = (ImageView) findViewById(R.id.btnWatchVideo);
btnWatchVideo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, VideoActivity.class));
}
});}
Try following the MediaPlayer tutorials on developer.android.com:
https://developer.android.com/guide/topics/media/mediaplayer.html
You need to change your code like this
package com.mobileappdev.spotstvhdlivestreamcric.activites;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.mobileappdev.spotstvhdlivestreamcric.R;
import com.mobileappdev.spotstvhdlivestreamcric.mediaplayer.ResizeSurfaceView;
import com.mobileappdev.spotstvhdlivestreamcric.mediaplayer.VideoControllerView;
import java.io.IOException;
public class MediaPlayerActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControlListener, MediaPlayer.OnVideoSizeChangedListener, MediaPlayer.OnCompletionListener {
private final static String TAG = MediaPlayerActivity.class.getSimpleName();
private ResizeSurfaceView mVideoSurface;
private MediaPlayer mMediaPlayer;
private VideoControllerView controller;
private int mVideoWidth;
private int mVideoHeight;
private View mContentView;
private View mLoadingView;
private boolean mIsComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
getSupportActionBar().hide();
mVideoSurface = (ResizeSurfaceView) findViewById(R.id.videoSurface);
mContentView = findViewById(R.id.video_container);
mLoadingView = findViewById(R.id.loading);
SurfaceHolder videoHolder = mVideoSurface.getHolder();
videoHolder.addCallback(this);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnVideoSizeChangedListener(this);
//(FrameLayout) findViewById(R.id.videoSurfaceContainer)
controller = new VideoControllerView.Builder(this, this)
.withVideoTitle("ADD VIDEO TITLE")
.withVideoSurfaceView(mVideoSurface)//to enable toggle display controller view
.canControlBrightness(true)
.canControlVolume(true)
.canSeekVideo(true)
.exitIcon(R.drawable.video_top_back)
.pauseIcon(R.drawable.ic_media_pause)
.playIcon(R.drawable.ic_media_play)
.shrinkIcon(R.drawable.ic_media_fullscreen_shrink)
.stretchIcon(R.drawable.ic_media_fullscreen_stretch)
.build((FrameLayout) findViewById(R.id.videoSurfaceContainer));//layout container that hold video play view
mLoadingView.setVisibility(View.VISIBLE);
try {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(this, Uri.parse("https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v"));
// mMediaPlayer.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mVideoSurface.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
controller.toggleControllerView();
return false;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// controller.show();
return false;
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mVideoHeight = mp.getVideoHeight();
mVideoWidth = mp.getVideoWidth();
if (mVideoHeight > 0 && mVideoWidth > 0)
mVideoSurface.adjustSize(mContentView.getWidth(), mContentView.getHeight(), mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mVideoWidth > 0 && mVideoHeight > 0)
mVideoSurface.adjustSize(getDeviceWidth(this), getDeviceHeight(this), mVideoSurface.getWidth(), mVideoSurface.getHeight());
}
private void resetPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public static int getDeviceWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(mDisplayMetrics);
return mDisplayMetrics.widthPixels;
}
public static int getDeviceHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(mDisplayMetrics);
return mDisplayMetrics.heightPixels;
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepareAsync();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
resetPlayer();
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
//setup video controller view
mLoadingView.setVisibility(View.GONE);
mVideoSurface.setVisibility(View.VISIBLE);
mMediaPlayer.start();
mIsComplete = false;
}
// End MediaPlayer.OnPreparedListener
/**
* Implement VideoMediaController.MediaPlayerControl
*/
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if (null != mMediaPlayer)
return mMediaPlayer.getCurrentPosition();
else
return 0;
}
#Override
public int getDuration() {
if (null != mMediaPlayer)
return mMediaPlayer.getDuration();
else
return 0;
}
#Override
public boolean isPlaying() {
if (null != mMediaPlayer)
return mMediaPlayer.isPlaying();
else
return false;
}
#Override
public boolean isComplete() {
return mIsComplete;
}
#Override
public void pause() {
if (null != mMediaPlayer) {
mMediaPlayer.pause();
}
}
#Override
public void seekTo(int i) {
if (null != mMediaPlayer) {
mMediaPlayer.seekTo(i);
}
}
#Override
public void start() {
if (null != mMediaPlayer) {
mMediaPlayer.start();
mIsComplete = false;
}
}
#Override
public boolean isFullScreen() {
return getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ? true : false;
}
#Override
public void toggleFullScreen() {
if (isFullScreen()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
#Override
public void exit() {
resetPlayer();
finish();
}
#Override
public void onCompletion(MediaPlayer mp) {
mIsComplete = true;
}
}
Your video is playing now.
I want to play music in my app when application starts. I tried many codes but nothing is working for me and i'm not getting any error.Can somebody please help me regarding this issue.Thanks in advance.
public class Login extends Activity {
EditText edName, edPassword;
String userName,password;
MediaPlayer mp;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mp = MediaPlayer.create(getApplicationContext(), R.raw.startsound);
ActionBar actionBar = getActionBar();
actionBar.hide();
edName = (EditText) findViewById(R.id.editText1);
edPassword = (EditText) findViewById(R.id.editText2);
mp.start();
}
public void SignInClick(View V) {
userName = edName.getText().toString();
password = edPassword.getText().toString();
if (userName.equals("")) {
Toast.makeText(Login.this, "Username is empty", Toast.LENGTH_LONG).show();}
else if (password.equals("")) {
Toast.makeText(Login.this, "Password is empty", Toast.LENGTH_LONG).show();
}
else {
Intent intent=new Intent(Login.this,Home.class);
startActivity(intent);
}
}
Hope this helps, and should be a working example although I have not had chance to test it.
public static Music theme;
theme = createMusic("menutheme.mp3");
theme.setLooping(true);
theme.setVolume(0.85f);
theme.play();
public Music createMusic(String filename) {
try {
AssetFileDescriptor assetDescriptor = assets.openFd(filename);
return new AndroidMusic(assetDescriptor);
} catch (IOException e) {
throw new RuntimeException("Couldn't load music '" + filename + "'");
}
}
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import com.matt.framework.Music;
import java.io.IOException;
public class AndroidMusic implements Music, OnCompletionListener, OnSeekCompleteListener, OnPreparedListener, OnVideoSizeChangedListener {
MediaPlayer mediaPlayer;
boolean isPrepared = false;
public AndroidMusic(AssetFileDescriptor assetDescriptor) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
assetDescriptor.getStartOffset(),
assetDescriptor.getLength());
mediaPlayer.prepare();
isPrepared = true;
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnVideoSizeChangedListener(this);
} catch (Exception e) {
throw new RuntimeException("Couldn't load music");
}
}
#Override
public void dispose() {
if (this.mediaPlayer.isPlaying()){
this.mediaPlayer.stop();
}
this.mediaPlayer.release();
}
#Override
public boolean isLooping() {
return mediaPlayer.isLooping();
}
#Override
public boolean isPlaying() {
return this.mediaPlayer.isPlaying();
}
#Override
public boolean isStopped() {
return !isPrepared;
}
#Override
public void pause() {
if (this.mediaPlayer.isPlaying())
mediaPlayer.pause();
}
#Override
public void play() {
if (this.mediaPlayer.isPlaying())
return;
try {
synchronized (this) {
if (!isPrepared)
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void setLooping(boolean isLooping) {
mediaPlayer.setLooping(isLooping);
}
#Override
public void setVolume(float volume) {
mediaPlayer.setVolume(volume, volume);
}
#Override
public void stop() {
if (this.mediaPlayer.isPlaying() == true){
this.mediaPlayer.stop();
synchronized (this) {
isPrepared = false;
}}
}
#Override
public void onCompletion(MediaPlayer player) {
synchronized (this) {
isPrepared = false;
}
}
#Override
public void seekBegin() {
mediaPlayer.seekTo(0);
}
#Override
public void onPrepared(MediaPlayer player) {
// TODO Auto-generated method stub
synchronized (this) {
isPrepared = true;
}
}
#Override
public void onSeekComplete(MediaPlayer player) {
// TODO Auto-generated method stub
}
#Override
public void onVideoSizeChanged(MediaPlayer player, int width, int height) {
// TODO Auto-generated method stub
}
}
I am a Android newbie. I want to design my personal videoplayer to play streaming music, so I use MediaPlayer and SurfaceView. The project plays streaming video successfully, but it can't be setloop. I have google many articles and read Android Developer. I can't figure out why mediaPlayer.setLooping(true) don't work here. Thanks^^
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
The code includes two parts: 1.Test_Videoplayer.java 2.Player.java
1.Test_Videoplayer.java
public class Test_Videoplayer extends Activity {
private SurfaceView surfaceView;
private Button btnPause, btnPlayUrl, btnStop;
private SeekBar skbProgress;
private Player player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView1);
btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);
btnPlayUrl.setOnClickListener(new ClickEvent());
btnPause = (Button) this.findViewById(R.id.btnPause);
btnPause.setOnClickListener(new ClickEvent());
btnStop = (Button) this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(new ClickEvent());
skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);
skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
player = new Player(surfaceView, skbProgress);
}
class ClickEvent implements OnClickListener {
#Override
public void onClick(View arg0) {
if (arg0 == btnPause) {
player.pause();
} else if (arg0 == btnPlayUrl) {
String url = "http://sites.google.com/site/ronforwork/Home/android-2/littleMonster.3gp";
player.playUrl(url);
} else if (arg0 == btnStop) {
player.stop();
}
}
}
class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
int progress;
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
this.progress = progress * player.mediaPlayer.getDuration()
/ seekBar.getMax();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.mediaPlayer.seekTo(progress);
}
}
}
2.Player.java <-- here is mediaPlayer.setLooping(true)
public class Player implements OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private int videoWidth;
private int videoHeight;
public MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SeekBar skbProgress;
private Timer mTimer = new Timer();
public Player(SurfaceView surfaceView, SeekBar skbProgress) {
this.skbProgress = skbProgress;
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mTimer.schedule(mTimerTask, 0, 1000);
}
TimerTask mTimerTask = new TimerTask() {
#Override
public void run() {
if (mediaPlayer == null)
return;
if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
handleProgress.sendEmptyMessage(0);
}
}
};
Handler handleProgress = new Handler() {
public void handleMessage(Message msg) {
int position = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (duration > 0) {
long pos = skbProgress.getMax() * position / duration;
skbProgress.setProgress((int) pos);
}
};
};
public void play() {
mediaPlayer.start();
}
public void playUrl(String videoUrl) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pause() {
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.e("mediaPlayer", "surface changed");
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
Log.e("mediaPlayer", "error", e);
}
Log.e("mediaPlayer", "surface created");
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.e("mediaPlayer", "surface destroyed");
}
#Override
public void onPrepared(MediaPlayer arg0) {
videoWidth = mediaPlayer.getVideoWidth();
videoHeight = mediaPlayer.getVideoHeight();
if (videoHeight != 0 && videoWidth != 0) {
arg0.start();
}
Log.e("mediaPlayer", "onPrepared");
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
skbProgress.setSecondaryProgress(bufferingProgress);
int currentProgress = skbProgress.getMax()
* mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
Log.e(currentProgress + "% play", bufferingProgress + "% buffer");
}
}
This is a pretty strange problem. I have a book that I have been going through (The Android Developer's Cookbook)
I am making a pretty basic app (at least, I think it is basic)
The problem I am having is this. When the service I create is stopped, the activity does the service's work.
I want to monitor the Z Axis reading on my phone (in the background, always)
Here is my project structure:
TiltMonitorActivity
TiltMonitorService
From TiltMonitorActivity:
#Override
public void onClick(View v) {
boolean error = false;
if (tbService.isChecked()) {
try {
startService(backgroundService);
}
catch (Exception e) {
error = true;
}
finally {
if (error)
{
errorToast();
}
}
}
else if (!tbService.isChecked()) {
try {
stopService(backgroundService);
}
catch (Exception e){
error = true;
}
finally {
if (error)
{
errorToast();
}
}
}
}
});
I also put this in onBackPressed(), onPause, onDestroy
finish();
The intent I create when starting/stopping service
final Intent backgroundService = new Intent(this, TiltMonitorService.class);
From TiltMonitorService:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.os.Vibrator;
import android.widget.Toast;
public class TiltMonitorService extends Service {
private SensorManager sensorManager = null;
private Vibrator vibrator = null;
private float[] accData = new float[3];
// These are for manual config
private float FORWARD_THRESHOLD = 5f;
private float BACKWARD_THRESHOLD = -5f;
// These are for auto config
// The phone will face forward, so a positive Z Axis means user is leaning backwards
// and that a negative Z Axis the user is leaning forward
private float AUTO_FORWARD_THRESHOLD = -1.5f;
private float AUTO_BACKWARD_THRESHOLD = 3.5f;
public static TiltMonitorActivity MAIN_ACTIVITY = null;
public static void setMainActivity(TiltMonitorActivity activity)
{
MAIN_ACTIVITY = activity;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
sensorManager.registerListener( tiltListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
}
private SensorEventListener tiltListener = new SensorEventListener() {
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
accData[0] = event.values[0];
accData[1] = event.values[1];
accData[2] = event.values[2];
checkData(accData);
}
};
private void checkData(float[] accData)
{
if ((accData[2] < AUTO_FORWARD_THRESHOLD) || (accData[2] > AUTO_BACKWARD_THRESHOLD))
{
vibrator.vibrate(100);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
}
Again, I get the Toast that the service has been started and stopped when hitting the ToggleButton in the activity.
But the task still happens. (Vibrates when below or above set thresholds)
When I open up a task killer, the service isn't running. Only the activity is (and killing it kills the vibration)
I'm not sure what words to search for, I couldn't find any one else with the same problem. I tried to post only relevant code in the Activity to avoid clutter. The service is posted in its entirety. If more is needed, I will put it up promptly.
Thanks you guys for any insight given
at a guess, because you register the listener in onCreate without unregistering it in onDestroy
in the service, that is.