Android MediaPlayer seekTo() function working incorrect - android

I have a problem when using MediaPlayer to play video from url.
The follow of program : create an activity to play video -> press Home button -> back to app.
The requirement is video play from start, when press Home button video continuos play(only audio), and when back to app, video must play continuous(combine movie and audio).
The first, I created a MediaPlayer variable to play video. When Home button is pressed, MediaPlayer play continuous. But when back to app, video cannot displayed(black screen). So, I created other MediaPlayer variable to solved this issue. But when I using seekTo() function to seek second MediaPlayer to position of first MediaPlayer, this function is working incorrect.
import java.io.IOException;
import com.example.videotest.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlayVideoActivity extends Activity implements OnClickListener,SurfaceHolder.Callback, FGMediaController.MediaPlayerControl {
SurfaceView videoSurface,videoSurfaceFullscreen,videoSurfaceSmallsceen;
MediaPlayer player, backupPlayer;
FGMediaController controller;
LinearLayout llControllerBar;
public boolean isFullscreen = false;
int videoDuration;
int videoCurrent;
SurfaceHolder viewHolder = null;
boolean isPaused = false;
String videoUrl = "http://cdn-smatopi.tv-bank.com/movie/867/867-32/867-32-2015042306-D3/hls/hls3/867-32-2015042306-D3-HLS3.m3u8";
Button btnSeek, btnRelease;
int currentPos = 30000;
boolean videoPrepared = false;
boolean backupPrepared = false;
boolean mVideoSizeIsSet = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.playvideo);
btnSeek = (Button) findViewById(R.id.btnSeek);
btnRelease = (Button) findViewById(R.id.btnRelease);
videoSurface = (SurfaceView)findViewById(getResources().getIdentifier("vvVideo", "id", getPackageName()));
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
backupPlayer = new MediaPlayer();
controller = new FGMediaController(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(videoUrl));
player.prepareAsync();
//backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//backupPlayer.setDataSource(this, Uri.parse(videoUrl));
//backupPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
btnSeek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("Huhu",currentPos + "");
backupPlayer.seekTo(currentPos);
}
});
btnRelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
backupPlayer.stop();
backupPlayer.release();
}
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(PlayVideoActivity.this);
controller.setAnchorView((FrameLayout) findViewById(PlayVideoActivity.this.getResources().getIdentifier("videoSurfaceContainer", "id", PlayVideoActivity.this.getPackageName())));
player.start();
}
});
}
#Override
public void onDestroy(){
//backupPlayer.release();
player.release();
super.onDestroy();
}
#Override
public void onResume(){
Log.e("Surface Created","OnResume");
super.onResume();
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e("Surface Created","Surface Created! " + holder);
if(viewHolder != null){
viewHolder = holder;
backupPlayer = new MediaPlayer();
try {
backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
backupPlayer.setDataSource(this, Uri.parse(videoUrl));
backupPlayer.prepareAsync();
backupPlayer.setDisplay(holder);
backupPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
backupPrepared = true;
backupPlayer.start();
}
});
backupPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
if (width == 0 || height == 0){
Toast.makeText(getApplicationContext(),"Width = 0 Height = 0"+ mp.getDuration(), Toast.LENGTH_LONG).show();
}else{
if(backupPrepared){
backupPrepared = false;
currentPos = player.getCurrentPosition();
player.reset();
Toast.makeText(getApplicationContext(),"Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos, Toast.LENGTH_LONG).show();
Log.e("Huhu","Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos);
backupPlayer.seekTo(currentPos); // If you set currentPos = 20000ms or 30000ms backupPlayer can to seek, but if you set currentPos = 10000ms backupPlayer cannot seek !
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
player.setDisplay(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("Surface Created","surfaceDestroyed! " + player.getCurrentPosition());
viewHolder = holder;
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
//Log.printLog(Log.ERROR, "CURRENT :"+player.getCurrentPosition());
int current = 0;
try{
current = player.getCurrentPosition();
}catch(Exception e){
e.printStackTrace();
}
return current;
}
#Override
public int getDuration() {
int duration = 0;
try{
duration = player.getDuration();
}catch(Exception e){
e.printStackTrace();
}
return duration;
}
#Override
public boolean isPlaying() {
boolean isPlaying = false;
try{
isPlaying = player.isPlaying();
}catch(Exception e){
e.printStackTrace();
}
return isPlaying;
}
#Override
public void pause() {
player.pause();
}
#Override
public void seekTo(int i) {
player.seekTo(i);
}
#Override
public void start() {
player.start();
}
#Override
public boolean isFullScreen() {
return isFullscreen;
}
#Override
public void toggleFullScreen() {
// TODO Auto-generated method stub
}
#Override
public void doBackPressed() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
}
}

Related

MediaController doesn't seem to show up

I have an android app with a detail activity, that detail activity has few tabs with underlying fragments. One of these fragments is plain list with a name of audio files when I click each line I'm playing the clicked audio files.
Everything works OK, but I would like to have some means of seeing a progress of the playback and ability to stop a playback, I was trying to add MediaController but even though I'm creating it without errors no media control is visible on a screen.
I'm not sure if I'm doing it in a correct way any help you would be appreciated.
Thanks a lot,
Radek
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.audio_row,parent,false);
}
TextView textView = (TextView) convertView.findViewById(R.id.rowText);
textView.setText("" + jsonAudio.getJSONObject(position).getString("description"));
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String audioFileName = jsonAudio.getJSONObject(position).getString("file");
Toast.makeText(context, "audio item clicked: " + audioFileName, Toast.LENGTH_SHORT).show();
AssetFileDescriptor descriptor = context.getAssets().openFd(audioFileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
MediaPlayer mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start, end);
mediaPlayer.prepare();
// not doing really anything
MediaController mediaController = new MediaController(context);
mediaController.setAnchorView(v);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Please check the below code for your refrence
In your code you have passed the TextView in the mediaController need to pass the SurfaceView instead of TextView and you need to set the MediaPlayer in the MediaController
JAVA file.
import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.util.Log;
import android.media.MediaPlayer.OnPreparedListener; import android.view.MotionEvent; import android.widget.MediaController; import android.widget.TextView;
import java.io.IOException;
public class AudioPlayer extends Activity implements OnPreparedListener, MediaController.MediaPlayerControl{ private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private MediaPlayer mediaPlayer; private MediaController mediaController; private String audioFile;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.audio_player);
audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
}
#Override protected void onStop() { super.onStop(); mediaController.hide(); mediaPlayer.stop(); mediaPlayer.release(); }
#Override public boolean onTouchEvent(MotionEvent event) { //the MediaController will hide after 3 seconds - tap the screen to make it appear again mediaController.show(); return false; }
//--MediaPlayerControl methods---------------------------------------------------- public void start() { mediaPlayer.start(); }
public void pause() { mediaPlayer.pause(); }
public int getDuration() { return mediaPlayer.getDuration(); }
public int getCurrentPosition() { return mediaPlayer.getCurrentPosition(); }
public void seekTo(int i) { mediaPlayer.seekTo(i); }
public boolean isPlaying() { return mediaPlayer.isPlaying(); }
public int getBufferPercentage() { return 0; }
public boolean canPause() { return true; }
public boolean canSeekBackward() { return true; }
public boolean canSeekForward() { return true; } //--------------------------------------------------------------------------------
public void onPrepared(MediaPlayer mediaPlayer) { Log.d(TAG, "onPrepared"); mediaController.setMediaPlayer(this); mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
} }
XML file-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_audio_view" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_gravity="center"
android:orientation="vertical"> <TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center" android:text="Now playing:"
android:textSize="25sp" android:textStyle="bold" /> <TextView
android:id="#+id/now_playing_text" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginTop="20dip"
android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
android:layout_gravity="center" android:text="Now playing.."
android:textSize="16sp" android:textStyle="italic" /> </LinearLayout>
I had to tweak Patrick's solution a bit to play the file from assets folder but it worked great, here is reformatted java file for easy cut and paste if anyone needs it.
import android.content.res.AssetFileDescriptor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.MotionEvent;
import android.widget.MediaController;
import android.widget.TextView;
import java.io.IOException;
public class MediaPlayer extends AppCompatActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private android.media.MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFileName = "item1_audio1.mp3";;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_audio_view);
((TextView) findViewById(R.id.now_playing_text)).setText(audioFileName);
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
AssetFileDescriptor descriptor = MediaPlayer.this.getAssets().openFd(audioFileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start, end);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFileName + " for playback.", e);
}
}
#Override
public void onPrepared(android.media.MediaPlayer mp) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
}
#Override
public boolean onTouchEvent(MotionEvent event) { //the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public void onStart() {
super.onStart();
}
}

Including .mp3 files in .apk

I'm currently working on Media Player. All is done except that i have .mp3 files in android emulator external storage. What i want to know is, how can i include all those .mp3 files to the .apk so that when i install the the app on phone, the files automatically transfer either on internal or external storage of the device.
I've gone through this issue but couldn't find best possible answer anywhere.
Please help me!
this is my code
VoiceService.java
package com.example.soundplayer;
import android.app.Service;
import java.util.ArrayList;
import android.content.ContentUris;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.PowerManager;
import android.util.Log;
import android.content.Intent;
import android.os.IBinder;
import java.util.Random;
import android.app.Notification;
import android.app.PendingIntent;
import com.example.soundplayer.Voice;
public class VoiceService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener{
//media player
private MediaPlayer player;
//song list
private ArrayList<Voice> songs;
//current position
private int songPosn;
private boolean shuffle=false;
private Random rand;
private String songTitle;
private static final int NOTIFY_ID=1;
private final IBinder musicBind = new MusicBinder();
public void onCreate()
{
//create the service
super.onCreate();
//initialize position
songPosn=0;
//create player
player = new MediaPlayer();
initMusicPlayer();
rand=new Random();
}
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
}
public void initMusicPlayer()
{
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Voice> theSongs){
songs=theSongs;
}
public class MusicBinder extends Binder
{
VoiceService getService() {
return VoiceService.this;
}
}
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return musicBind;
}
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
public void playSong(){
//play a song
player.reset();
//get song
Voice playSong = songs.get(songPosn);
songTitle=playSong.getTitle();
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try
{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e)
{
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
public void setSong(int songIndex){
songPosn=songIndex;
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
if(player.getCurrentPosition()>=0){
mp.reset();
playNext();
}
}
#Override
public void onDestroy() {
stopForeground(true);
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
Intent notIntent = new Intent(this, MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songTitle);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
public int getPosn(){
return player.getCurrentPosition();
}
public int getDur(){
return player.getDuration();
}
public boolean isPng(){
return player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
public void seek(int posn){
player.seekTo(posn);
}
public void go(){
player.start();
}
public void playPrev(){
songPosn--;
if(songPosn>=0) songPosn=songs.size()-1;
playSong();
}
public void playNext(){
if(shuffle){
int newSong = songPosn;
while(newSong>=songPosn){
newSong=rand.nextInt(songs.size());
}
songPosn=newSong;
}
else{
songPosn++;
if(songPosn==songs.size()) songPosn=0;
}
playSong();
}
}
MainActivity.java
package com.example.soundplayer;
import android.app.Activity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import android.widget.MediaController.MediaPlayerControl;
import com.example.soundplayer.VoiceService.MusicBinder;
import android.net.Uri;
import android.content.ContentResolver;
import android.database.Cursor;
import android.widget.ListView;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.os.IBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity implements MediaPlayerControl{
private ArrayList<Voice> songList;
private ListView songView;
private VoiceService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private VoiceController controller;
private boolean paused=false, playbackPaused=false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songView = (ListView)findViewById(R.id.song_list);
songList = new ArrayList<Voice>();
getSongList();
Collections.sort(songList, new Comparator<Voice>(){
public int compare(Voice a, Voice b){
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
setController();
}
private void setController(){
//set the controller up
controller = new VoiceController(this);
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.song_list));
controller.setEnabled(true);
}
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
protected void onPause(){
super.onPause();
paused=true;
}
#Override
protected void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
protected void onStop() {
controller.hide();
super.onStop();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, VoiceService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_shuffle:
musicSrv.setShuffle();
break;
case R.id.action_end:
stopService(playIntent);
musicSrv=null;
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
public void getSongList() {
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Voice(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void start() {
// TODO Auto-generated method stub
musicSrv.go();
}
#Override
public void pause() {
// TODO Auto-generated method stub
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public void seekTo(int pos) {
// TODO Auto-generated method stub
musicSrv.seek(pos);
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean canPause() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean canSeekBackward() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean canSeekForward() {
// TODO Auto-generated method stub
return true;
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}
just copy your .mp3 files into res/raw folder and read them
mp = MediaPlayer.create(context, R.raw.fileName);

Application crash with no exception after resuming

I am making simple app to display video and plaing audio playback if activity is in background.
My app works fine if i just turn screen off/on.
It crashes when I resume my app after brawsing another application.
Log cat show no error.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.squareup.otto.Subscribe;
public class MainActivity
extends Activity
implements android.view.SurfaceHolder.Callback {
private SurfaceView surfaceViewFrame;
private SurfaceHolder holder;
private Bundle extras;
private static final String TAG = "log_tag";
private boolean b = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceView);
surfaceViewFrame.setClickable(false);
holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
}
#Subscribe
public void attachPlayer(MediaPlayer player) {
player.setDisplay(holder);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
startService(new Intent(this, MediaPlayerService.class));
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
protected void onStart() {
super.onStart();
BusProvider.getInstance().register(this);
}
#Override
protected void onStop() {
super.onStop();
BusProvider.getInstance().unregister(this);
}
Service
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class MediaPlayerService
extends Service
implements MediaPlayer.OnPreparedListener,
MediaPlayer.OnCompletionListener,
MediaPlayer.OnSeekCompleteListener {
private static final String TAG = "MediaService";
private static final String ACTION_PLAY = "com.example.action.PLAY";
private MediaPlayer player;
public String[]
video_path =
{"https://ellovidsout.s3.amazonaws.com/1265/9/1422967594.mp4.m3u8", "https://ellovidsout.s3.amazonaws.com/1260/9/1422887544.mp4.m3u8"};
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
playVideo();
Notification note = new Notification(
R.drawable.ic_launcher, "Can you hear the music?", System.currentTimeMillis()
);
Intent i = new Intent(this, MediaPlayerService.class);
i.setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
);
PendingIntent pi = PendingIntent.getActivity(
this, 0, i, 0
);
note.setLatestEventInfo(
this, "Fake Player", "Now Playing: \"Ummmm, Nothing\"", pi
);
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(1337, note);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.release();
player = null;
}
private Thread playback = new Thread(
new Runnable() {
public void run() {
try {
try {
player.setDataSource(
MediaPlayerService.this, Uri.parse(
video_path[0]
)
);
player.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
}
}
);
private void playVideo() {
if (player!=null&&!playback.isAlive()) playback.start();
}
public void onPrepared(MediaPlayer mp) {
if (!player.isPlaying()) {
player.start();
BusProvider.getInstance()
.post(player);
}
}
public void onCompletion(MediaPlayer mp) {
try {
player.setDataSource(
MediaPlayerService.this, Uri.parse(
video_path[0]
)
);
} catch (IOException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
player.prepareAsync();
}
public void onSeekComplete(MediaPlayer mp) {
}
}
you missed in onStop:
#Override
protected void onStop() {
holder.removeCallback(this);
super.onStop();
}
please add the crash report

Android MediaPlayer - onBackPressed() not working

I have an app which just plays the same video in loop. Everything works as expected, except for one thing:
I want to stop the playback if I press the back button, but I am not able to get it to work. My activity simply ignore that I press it and instead I get an ANR. I thought that using onBackPressed() should handle this case.
Can anyone tell me, what I am doing wrong???
Here is my code:
package dk.test.videoplayer;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, OnClickListener {
private SurfaceView mSurfaceView = null;
private SurfaceHolder mSurfaceHolder = null;
private String videoPath;
private MediaPlayer mMediaPlayer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("onCreate called");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.TYPE_APPLICATION_PANEL |
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
mSurfaceView = new SurfaceView(this);
setContentView(mSurfaceView);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
videoPath = "android.resource://dk.beatpro.videoplayer/raw/demo_video";
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
}
catch (Exception e) {
System.out.println(e.toString());
}
}
#Override
protected void onResume() {
super.onResume();
System.out.println("onResume called");
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
}
#Override
public void onPrepared(MediaPlayer mp) {
System.out.println("onPrepared called");
if (!mMediaPlayer.isPlaying())
mMediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
System.out.println("onCompletion() called");
playVideo();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
System.out.println("onPause() called");
releaseMediaPlayer();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
releaseMediaPlayer();
}
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("surfaceCreated() called");
mMediaPlayer.setDisplay(mSurfaceHolder);
playVideo();
}
private void playVideo() {
System.out.println("playVideo() called");
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(this, Uri.parse(videoPath));
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.prepareAsync();
}
catch (Exception e) {
System.out.println(e.toString());
}
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying())
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println("surfaceChanged() called");
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("surfaceDestroyed() called");
}
#Override
public void onBackPressed() {
System.out.println("onBackPressed() called");
releaseMediaPlayer();
super.onBackPressed();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Toast.makeText(this, "Touch event", Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
#Override
public void onClick(View v) {
System.out.println("onClick() called");
Toast.makeText(this, "Click click", Toast.LENGTH_SHORT).show();
}
}
Call super.onBackPressed(); before your code in onBackPressed(..)
#Override
public void onBackPressed() {
super.onBackPressed();
System.out.println("onBackPressed() called");
releaseMediaPlayer();
}
Just call super.onBackPressed before releasing media player.
EDIT:
Also try removing the
mMediaPlayer=null;
statement in your releaseMediaPlayer() method.

setBackgroundResource of TextView in listitem

I've got an activity that presents a listview of tracks of songs. When an item is clicked, it streams the appropriate media file. I have a textview in each row that displays the length of the track. When the track is playing, I switch the backgroundresource of the textview in the row to a pause button drawable. In other words, when it's ready to play, it displays a play button and when its currently playing it displays a pause button. Simple enough....
Currently, I'm doing something like this to set the drawable to pause button if the mediaplayer is playing:
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
I'm doing this in my Runnable which has the mediaplayer callback of onPrepared.
Problem is that I need the drawable to be set in THAT list item, i.e. the one which was clicked and whose track is being played. How can I grab hold of which one was clicked and set ITS textview to the new drawable?
Here's the full code:
package com.me.player
import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.mtv.datahandler.Artist;
import com.mtv.datahandler.DataBaseHelper;
import com.mtv.datahandler.Track;
import com.mycompany.http.HttpRequest;
public class ArtistAudio extends ControllerActivity implements OnCompletionListener, OnPreparedListener, OnErrorListener{
private int METHOD_TYPE = 0;
private static final int GET_AUDIO = 1;
int CURRENT_POSITION = 0;
int DURATION = 0;
public static final String AUDIO_FEED_URL = "http://direct.rhapsody.com/metadata/data/getTopTracksForArtist.xml?blabla";
public static final int MAX_TRACKS = 200;
ArrayList<Track> tracks = new ArrayList<Track>();
Artist artist;
private MediaPlayer mp;
private int mSongPlaying = 0;
TextView _player;
#Override
protected void progressRunnableComplete() {
if(isFinishing()){
return;
}
if(METHOD_TYPE == GET_AUDIO){
setList();
}
}
public void setList(){
ListView listview = (ListView)findViewById(R.id.ListView01);
// ListView listview = (ListView)findViewById(R.id.ListView01);
if(listview == null){
setContent(R.layout.artistaudio);
listview = (ListView)findViewById(R.id.ListView01);
}
// listview.addHeaderView();
listview.setCacheColorHint(0);
listview.setAdapter(new TrackListAdapter());
listview.setSelector(R.drawable.listbackground);
listview.setDividerHeight(1);
listview.setDivider(getResources().getDrawable(R.drawable.img_dotted_line_horz));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
TrackClicked(arg2);
}
});
}
public void TrackClicked(int arg2){
mSongPlaying = arg2;
Track track = tracks.get(arg2);
String url = track.requestInfo("previewURL");
mHandler.post(new PlaySong(url));
// mHandler.post(new PlaySong("http://dc237.4shared.com/img/315443275/33f14ef2/dlink__2Fdownload_2F9y5VGjVt_3Ftsid_3D20100705-131850-40aa0b87/preview.mp3"));
}
public void setDuration(int n) {
DURATION = n;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Audio Clips");
setContent(R.layout.artistaudio);
Object o = getIntent().getParcelableExtra("artist");
if(o!=null){
artist = (Artist)o;
}
progressRunnable(new Runnable(){
public void run(){
getTracks();
}
}, "Loading. Please Wait...",false);
}
protected void getTracks() {
METHOD_TYPE = GET_AUDIO;
if(!DataBaseHelper.isOnline(this)){
RUNNABLE_STATE = RUNNABLE_FAILED;
return;
}
HttpRequest req;
try {
req = new HttpRequest(new URL(AUDIO_FEED_URL+artist.requestInfo("rhapsodyID")));
Document doc = req.AutoXMLNoWrite();
NodeList items = doc.getElementsByTagName("e");
tracks= new ArrayList<Track>();
for(int i=0; i<items.getLength(); i++){
Track newsitem = new Track(items.item(i));
tracks.add(newsitem);
}
RUNNABLE_STATE = RUNNABLE_SUCCESS;
} catch (Throwable e) {
RUNNABLE_STATE = RUNNABLE_FAILED;
e.printStackTrace();
}
}
public void onPause(){
super.onPause();
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.release();}catch(Exception e){e.printStackTrace();}
mp = null;
}
private class TrackListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return tracks.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return tracks.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
AudioCell blogView = null;
if (convertView != null) {
if(convertView.getClass() == TextView.class){
convertView = null;
}
}
if (convertView == null) {
blogView = new AudioCell(parent.getContext());
}
else {
blogView = (AudioCell) convertView;
}
blogView.display(position);
return blogView;
}
}
/** this class is responsible for rendering the data in the model, given the selection state */
class AudioCell extends RelativeLayout {
TextView _title;
int currentPosition;
public AudioCell(Context mContext) {
super(mContext);
_createUI(mContext);
}
/** create the ui components */
private void _createUI(Context m) {
RelativeLayout.LayoutParams params;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
_player = new TextView(m);
_player.setId(2);
_player.setBackgroundResource(R.drawable.playbtn);
_player.setText(":30");
addView(_player);
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
_player.setLayoutParams(params);
_title = new TextView(m);
_title.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
params.addRule(RelativeLayout.RIGHT_OF, _player.getId());
params.setMargins(0, 10, 0, 10);
_title.setGravity(Gravity.CENTER_VERTICAL);
_title.setLayoutParams(params);
_title.setId(102);
addView(_title);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
// _player.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// PlaySong.PlaySong("http://http://www.noiseaddicts.com/samples/2544.mp3");
//
// }
// });
//
}
/** update the views with the data corresponding to selection index */
public void display(int index) {
_title.setText(tracks.get(index).requestInfo("name"));
}
}
private class PlaySong implements Runnable{
String songURL;
public PlaySong(String url){
songURL = url;
}
public void run(){
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
if(mp==null){
createPlayer();
}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.setAudioStreamType(AudioManager.STREAM_MUSIC);}catch(Exception e){e.printStackTrace();}
try{mp.setDataSource(songURL);}catch(Exception e){e.printStackTrace();}
try{mp.prepareAsync();}catch(Exception e){e.printStackTrace();}
}
}
public void createPlayer(){
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try{mp.reset();}catch(Exception e){e.printStackTrace();}
// if(mSongPlaying<tracks.size()-1)
// {
// TrackClicked(mSongPlaying+1);
// }
_player.setBackgroundResource(R.drawable.playbtn);
}
#Override
public void onPrepared(MediaPlayer inMP) {
// TODO Auto-generated method stub
mp.start();
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
}
As you can see, my inner class AudioCell which extends RelativeLayout is what I'm using for the rows of my ListView....
Any thoughts? Where should I be setting the drawable and how can I make sure it does it only for the row that was clicked (i.e. for the track that's actually being played).
change the TrackClicked method's siggnature. pass both arg1 and arg3 from onItemClick and in the TrackClicked method do this arg1.setBackgroundResource(R.drawable.thebackground);
Inside your TrackClicked method, add this:
getAdapter().getChildAt(arg2).setBackgroundResource(R.drawable.thebackground);

Categories

Resources