I am creating an application in that i need continuous speech recognition. But onReadyForSpeech calling two times.
I am also attaching my code. Please help me to find out the problem.
Thanks in advance.
private SpeechRecognizer mSpeechRecognizer = null;
public static VoiceRecognizeService sVoiceRecognizeService;
private ITelephony mListener;
private boolean isListening;
private Intent mSaverController;
public VoiceRecognizeService() {
super();
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sVoiceRecognizeService = this;
startListening();
return START_NOT_STICKY;
}
public void setTelephonyListener(ITelephony mListener) {
this.mListener = mListener;
}
public static VoiceRecognizeService getInstance() {
return sVoiceRecognizeService;
}
// starts the service
public void startListening() {
if (!isListening) {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(this);
Intent mRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_IN");
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 2000);
mRecognizerIntent.putExtra("android.speech.extra.DICTATION_MODE", true);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, false);
mRecognizerIntent.putExtra("android.speech.extra.PREFER_OFFLINE", true);
mRecognizerIntent.putExtra("calling_package", this.getPackageName());
mSpeechRecognizer.startListening(mRecognizerIntent);
isListening = true;
}
}
public void processVoiceCommands(final ArrayList<String> partialData) {
}
public void restartListeningService() {
cancelSpeechRecognition();
startListening();
}
public void cancelSpeechRecognition() {
if (mSpeechRecognizer != null) {
mSpeechRecognizer.stopListening();
mSpeechRecognizer.cancel();
mSpeechRecognizer.destroy();
mSpeechRecognizer = null;
isListening = false;
}
}
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.e("VoiceError", "speechReady");
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float scale) {
if (mListener != null) {
mListener.onRmsChanged(scale);
}
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
if (i == SpeechRecognizer.ERROR_RECOGNIZER_BUSY) {
} else {
restartListeningService();
}
}
#Override
public void onResults(Bundle bundle) {
final ArrayList<String> data = bundle.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
if (data != null) {
processVoiceCommands(data);
}
restartListeningService();
}
#Override
public void onPartialResults(Bundle bundle) {
final ArrayList<String> data = bundle.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
Log.e("VoiceError", "partialResults " + data);
}
#Override
public void onEvent(int i, Bundle bundle) {
}
#Override
public void onDestroy() {
if (mSpeechRecognizer != null) {
mSpeechRecognizer.setRecognitionListener(null);
cancelSpeechRecognition();
}
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
Related
Mediabrowsercompat not playing the music when app goes background. If I don't disconnect the mediabrowsercompat instance in activity onStop method then it is working. But that is not the solution as according to documentation we have to disconnect the service once app goes background.
This is my mediabroweserservicecomat class (I am using Exoplayer to play music):
private static final String PLAYBACK_CHANNEL_ID = "100";
private static final int PLAYBACK_NOTIFICATION_ID =101 ;
private MediaSessionCompat mediaSessionCompat;
private PlaybackStateCompat.Builder stateBuilder;
private SimpleExoPlayer exoPlayer;
private Uri oldUri;
private AudioAttributes audioAttributes;
private PlayerNotificationManager playerNotificationManager;
#Override
public void onCreate() {
super.onCreate();
Log.i("Test","Hi");
initPlayer();
initAttributes();
ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
mediaSessionCompat = new MediaSessionCompat(getApplicationContext(), "Tag", mediaButtonReceiver, null);
mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS|
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
stateBuilder = new PlaybackStateCompat.Builder();
stateBuilder.setActions(PlaybackStateCompat.ACTION_PLAY|PlaybackStateCompat.ACTION_PLAY_PAUSE);
mediaSessionCompat.setPlaybackState(stateBuilder.build());
mediaSessionCompat.setCallback(mediaSessionCompatCallback);
setSessionToken(mediaSessionCompat.getSessionToken());
mediaSessionCompat.setActive(true);
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setClass(this, MediaButtonReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
mediaSessionCompat.setMediaButtonReceiver(pendingIntent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaButtonReceiver.handleIntent(mediaSessionCompat,intent);
return super.onStartCommand(intent, flags, startId);
}
private MediaSessionCompat.Callback mediaSessionCompatCallback = new MediaSessionCompat.Callback() {
#Override
public void onPlayFromUri(Uri uri, Bundle extras) {
super.onPlayFromUri(uri, extras);
if (uri!=null){
MediaItem mediaSource = MediaItem.fromUri(uri);
if (uri!=oldUri){
play(mediaSource);
onPlay();
}else {
oldUri = uri;
}
}
}
#Override
public void onPlay() {
super.onPlay();
Log.i("onPlay","onPlay");
//startService(new Intent(MusicService.this,MusicForegroundService.class));
playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(MusicService.this,
PLAYBACK_CHANNEL_ID, R.string.channel_name, PLAYBACK_NOTIFICATION_ID,
new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public CharSequence getCurrentContentTitle(Player player) {
return "title";
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
Intent intent = new Intent(getBaseContext(), PlayerFullViewActivity.class);
return PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
#Nullable
#Override
public CharSequence getCurrentContentText(Player player) {
return "content";
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
},
new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
startForeground(notificationId,notification);
}
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
stopSelf();
}
});
playerNotificationManager.setPlayer(exoPlayer);
}
#Override
public void onPause() {
super.onPause();
pause();
}
#Override
public void onStop() {
playerNotificationManager.setPlayer(null);
super.onStop();
stop();
}
};
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
private void stop() {
exoPlayer.setPlayWhenReady(false);
exoPlayer.release();
exoPlayer =null;
updatePlayBackState(PlaybackStateCompat.STATE_NONE);
mediaSessionCompat.setActive(false);
mediaSessionCompat.release();
}
#SuppressLint("WrongConstant")
private void pause() {
if (exoPlayer!=null){
exoPlayer.setPlayWhenReady(false);
if (exoPlayer.getPlaybackState()==PlaybackStateCompat.STATE_PLAYING){
updatePlayBackState(PlaybackStateCompat.STATE_PAUSED);
}
}
}
private void play(MediaItem mediaSource){
if (exoPlayer==null) {
initPlayer();
}
if (audioAttributes==null) {
initAttributes();
}
exoPlayer.setAudioAttributes(audioAttributes,true);
exoPlayer.setMediaItem(mediaSource);
exoPlayer.prepare();
play();
}
private void initAttributes() {
audioAttributes = new AudioAttributes.Builder().setUsage(C.USAGE_MEDIA)
.setContentType(C.CONTENT_TYPE_MUSIC)
.build();
}
private void initPlayer() {
exoPlayer = new SimpleExoPlayer.Builder(this, new DefaultRenderersFactory(getBaseContext()),
new DefaultExtractorsFactory()).build();
}
private void play() {
exoPlayer.setPlayWhenReady(true);
updatePlayBackState(PlaybackStateCompat.STATE_PLAYING);
mediaSessionCompat.setActive(true);
}
private void updatePlayBackState(int statePlaying) {
mediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().
setState(statePlaying,0L,0).build());
}
#Nullable
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid, #Nullable Bundle rootHints) {
return new BrowserRoot("",null);
}
#Override
public void onLoadChildren(#NonNull String parentId, #NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
result.sendResult(null);
}
This is my activity class:
ActivityPlayerFullViewBinding activityPlayerFullViewBinding;
private MediaBrowserCompat mediaBrowserCompat;
private MediaBrowserCompat.ConnectionCallback connectionCallback = new MediaBrowserCompat.ConnectionCallback(){
#Override
public void onConnected() {
super.onConnected();
MediaSessionCompat.Token sessionToken = mediaBrowserCompat.getSessionToken();
if (sessionToken!=null){
try {
MediaControllerCompat mediaControllerCompat = new
MediaControllerCompat(PlayerFullViewActivity.this, sessionToken);
MediaControllerCompat.setMediaController(PlayerFullViewActivity.this,mediaControllerCompat);
playPauseBuild();
Log.d("onConnected","ConnectionSuccess");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
#Override
public void onConnectionFailed() {
super.onConnectionFailed();
Log.d("onConnectionFaild","ConnectionFailed");
}
};
MediaControllerCompat.Callback controllerCallback =
new MediaControllerCompat.Callback() {
#Override
public void onMetadataChanged(MediaMetadataCompat metadata) {}
#Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityPlayerFullViewBinding = DataBindingUtil.setContentView(this,R.layout.activity_player_full_view);
ComponentName componentName = new ComponentName(this,MusicService.class);
mediaBrowserCompat = new MediaBrowserCompat(this,componentName,connectionCallback,null);
}
private void playPauseBuild() {
MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(PlayerFullViewActivity.this);
activityPlayerFullViewBinding.playPauseBtn
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int state = mediaController.getPlaybackState().getState();
if (state== PlaybackStateCompat.STATE_PAUSED||state==PlaybackStateCompat.STATE_STOPPED||
state==PlaybackStateCompat.STATE_NONE){
mediaController.getTransportControls().playFromUri(
Uri.parse("https://www.mboxdrive.com/Eminem-Sing-For-The-Moment9jamo.com_.mp3"),null);
activityPlayerFullViewBinding.playPauseBtn.setText("Pause");
}else if (state == PlaybackStateCompat.STATE_PLAYING ||
state == PlaybackStateCompat.STATE_BUFFERING ||
state == PlaybackStateCompat.STATE_CONNECTING){
mediaController.getTransportControls().pause();
activityPlayerFullViewBinding.playPauseBtn.setText("Play");
}
}
});
mediaController.registerCallback(controllerCallback);
}
#Override
protected void onStart() {
super.onStart();
mediaBrowserCompat.connect();
}
#Override
public void onResume() {
super.onResume();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
#Override
protected void onStop() {
super.onStop();
Log.i("onStop","onStop");
MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(this);
if (mediaController != null) {
mediaController.unregisterCallback(controllerCallback);
}
mediaBrowserCompat.disconnect();
}
After wasting 2 sleepless nights. I found a workaround. I don't know whether it's a correct way to handle this. But if you have ever faced this problem. You can try it:
#Override
protected void onStart() {
super.onStart();
if (!mediaBrowserCompat.isConnected())
mediaBrowserCompat.connect();
}
#Override
protected void onStop() {
super.onStop();
Log.i("onStop","onStop");
MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(this);
if (mediaController != null) {
mediaController.unregisterCallback(controllerCallback);
}
// mediaBrowserCompat.disconnect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaBrowserCompat.disconnect();
}
When I click music notification and run activity. When music change the content of textview changed, but view not update, but when I run an activity independently, everything works fine and view updated.
In musicService class:
PendingIntent contentPendingIntent = PendingIntent.getActivity
(this, 0, new Intent(this, MusicPlayer.class), 0);
builder.setContentTitle(mMedia.getTitleMedia())
.setContentText(mMedia.getSingerName())
.setContentIntent(contentPendingIntent)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(restartAction)
.addAction(playPauseAction)
.addAction(nextMusic)
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(getApplicationContext(), PlaybackStateCompat.ACTION_STOP));
and my activity class
public class MusicPlayer extends AppCompatActivity implements ServiceConnection, CacheListener, SeekBar.OnSeekBarChangeListener, Player.EventListener {
private SimpleExoPlayerView mPlayerView;
public PlayerService mPlayerService;
private boolean mBound;
//______________________________________________________________________________________________
VolleyRequestHelper volleyRequestHelper;
//______________________________________________________________________________________________
public static MusicPlayer instance;
public ImageView download;
TextView title;
TextView artist;
SeekBar progressBar;
ImageView circleImageView;
ImageView album_art_blurred;
PlayPauseButton mPlayPause;
public AppBarLayout appBarLayout;
private final VideoProgressUpdater updater = new VideoProgressUpdater();
public DownloadProgressView downloadProgressView;
//______________________________________________________________________________________________
TextView songElapsedTime;
TextView songDuration;
int positionOfMusic = 0;
public Media media;
boolean initAlbum = false;
boolean startService = false;
boolean checkChangeMediaDetails = true;
//______________________________________________________________________________________________
RecyclerView recyclerViewArtist;
SimilarSongsAdapter similarSongsAdapter;
public List<Media> similarSongsList = new ArrayList<>();
//______________________________________________________________________________________________
int songElapsed = 0;
int songDurationTime = 0;
int videoProgress = 0;
int mediaServiceRun = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
instance = this;
volleyRequestHelper = VolleyRequestHelper.getInstance(getApplicationContext(), requestCompletedListener);
initView();
initRecyclerview();
Intent intent = getIntent();
mediaServiceRun = intent.getIntExtra("mediaServiceRun", 1);
if (mediaServiceRun == 1) {
Intent i = new Intent(this, PlayerService.class);
bindService(i, this, Context.BIND_AUTO_CREATE);
startService(i);
} else {
media = intent.getParcelableExtra("media");
switch (media.getCustomMediaType()) {
case "آهنگ آلبوم":
setMedia(media);
getAlbumTrack(media.getAlbumId());
break;
case "آلبوم":
initAlbum = true;
getAlbumTrack(media.getId());
break;
default:
setMedia(media);
Serach(media.getSingerName(), "1");
break;
}
selectMedia(media);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(this);
mBound = false;
}
}
#Override
protected void onResume() {
super.onResume();
updater.start();
}
#Override
public void onPause() {
super.onPause();
updater.stop();
}
//_________________________ServiceConnected_and_ServiceDisconnected_____________________________
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
//______________________________________________________________________________________________
//_______________________________________setMediaInView_________________________________________
public void setMedia(Media mediaL) {
media = mediaL;
bluredImage(mediaL.getCover());
Picasso.with(this).load(mediaL.getCover()).into(circleImageView);
title.setText(mediaL.getTitleMedia());
artist.setText(mediaL.getSingerName());
checkCachedState(mediaL.getStreamUrl());
checkChangeMediaDetails = false;
}
public void bluredImage(String IMAGE_URL) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
album_art_blurred.setImageBitmap(BlurImage.fastblur(bitmap, 1f, 50));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
album_art_blurred.setImageResource(R.mipmap.ic_launcher);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
album_art_blurred.setTag(target);
Picasso.with(this)
.load(IMAGE_URL)
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into(target);
}
//______________________________________________________________________________________________
//______________________________________initView________________________________________________
public void initRecyclerview() {
recyclerViewArtist = (RecyclerView) findViewById(R.id.queue_recyclerview_horizontal);
recyclerViewArtist.setNestedScrollingEnabled(false);
recyclerViewArtist.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
LinearLayoutManager horizontalLayoutManagaertwo
= new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerViewArtist.setLayoutManager(horizontalLayoutManagaertwo);
similarSongsAdapter = new SimilarSongsAdapter(this, similarSongsList, recyclerViewArtist);
recyclerViewArtist.setAdapter(similarSongsAdapter);
}
public void initView() {
mPlayerView = (SimpleExoPlayerView) findViewById(R.id.simpleExoPlayerView);
appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
downloadProgressView = (DownloadProgressView) findViewById(R.id.downloadProgressView);
downloadProgressView.setPercentageColor(Color.parseColor("#ffffff"));
downloadProgressView.setDownloadedSizeColor(Color.parseColor("#ffffff"));
downloadProgressView.setTotalSizeColor(Color.parseColor("#ffffff"));
songElapsedTime = (TextView) findViewById(R.id.song_elapsed_time);
songDuration = (TextView) findViewById(R.id.song_duration);
progressBar = (SeekBar) findViewById(R.id.song_progress);
progressBar.setOnSeekBarChangeListener(this);
circleImageView = (ImageView) findViewById(R.id.album_art);
album_art_blurred = (ImageView) findViewById(R.id.album_art_blurred);
title = (TextView) findViewById(R.id.song_title);
artist = (TextView) findViewById(R.id.song_artist);
mPlayPause = (PlayPauseButton) findViewById(R.id.playpause);
download = (ImageView) findViewById(R.id.download);
if (SornaDownloadManager.inQueue) {
if (SornaDownloadManager.checkDownloadId(media.getId())) {
download.setVisibility(View.GONE);
downloadProgressView.show(SornaDownloadManager.lastDownloadID,
new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
}
}
}
//______________________________________________________________________________________________
//_________________________________Cache_and_UpdateProgressBar__________________________________
private void checkCachedState(String url) {
HttpProxyCacheServer proxy = TimberApp.getProxy(this);
boolean fullyCached = proxy.isCached(url);
if (fullyCached) {
progressBar.setSecondaryProgress(100);
}
proxy.registerCacheListener(this, url);
}
private void updateVideoProgress() {
if (mPlayerService != null)
try {
videoProgress = (int) (mPlayerService.getExoPlayer().getCurrentPosition() * 100 / mPlayerService.getExoPlayer().getDuration());
} catch (Exception e) {
}
progressBar.setProgress(videoProgress);
}
private final class VideoProgressUpdater extends Handler {
public void start() {
sendEmptyMessage(0);
}
public void stop() {
removeMessages(0);
}
#Override
public void handleMessage(Message msg) {
updateVideoProgress();
sendEmptyMessageDelayed(0, 500);
if (mPlayerService != null) {
try {
songElapsed = (int) mPlayerService.getExoPlayer().getCurrentPosition();
songDurationTime = (int) mPlayerService.getExoPlayer().getDuration();
} catch (Exception e) {
}
}
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(songElapsed));
songDuration.setText(millisecondsTOminutes.milliSecondsToTimer(songDurationTime));
}
}
#Override
public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
progressBar.setSecondaryProgress(percentsAvailable);
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
void seekVideo() {
int videoPosition = (int) (mPlayerService.getExoPlayer().getDuration() * progressBar.getProgress() / 100);
mPlayerService.getExoPlayer().seekTo(videoPosition);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekVideo();
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(mPlayerService.getExoPlayer().getCurrentPosition()) + "");
}
//______________________________________________________________________________________________
//____________________________________setButtonsFuction_________________________________________
public void setFunc(View v) {
switch (v.getId()) {
case R.id.playpause:
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
if (!startService) {
setStopService();
setStartService();
onlinePlay(media.getId());
} else {
mPlayerService.playTrack();
}
} else {
setPlayButton(false);
mPlayerService.pauseTrack();
}
break;
case R.id.next:
mPlayerService.nextTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.previous:
mPlayerService.previousTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.download:
showPopup(media);
break;
case R.id.share:
share.shareTrack(media, this);
break;
}
}
public void showPopup(final Media media) {
View popupView = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);
final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT
, WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 1, 1);
Button dnlow = (Button) popupView.findViewById(R.id.dnlow);
Button dnhigh = (Button) popupView.findViewById(R.id.dnhigh);
if (media.getDownloadLinksList128().matches("noLink"))
dnlow.setVisibility(View.GONE);
if (media.getDownloadLinksList320().matches("noLink"))
dnhigh.setVisibility(View.GONE);
dnlow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList128(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
dnhigh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList320(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(popupView, 0, 0);
}
//______________________________________________________________________________________________
//__________________________________GetDataFromServer___________________________________________
public void Serach(String searchQuery, String page) {
updateData();
volleyRequestHelper.RequestFetchSearchMedia
(constantsURL.REQUEST_FETCH_SIMILAR_SONGS, searchQuery, page, false);
}
public void getAlbumTrack(String albumId) {
updateData();
volleyRequestHelper.RequestFetchAlbumTrack
(constantsURL.REQUEST_FETCH_ALBUM_TRACKS, albumId, false);
}
public void selectMedia(final Media media) {
if (!constants.refLogId.matches(""))
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "selectSearchResult", media.getId(), constants.refLogId, false);
}
public void onlinePlay(final String mediaid) {
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "onlinePlay", mediaid, constants.refLogId, false);
}
public void updateData() {
similarSongsAdapter.notifyDataSetChanged();
similarSongsAdapter.setLoaded();
}
public void parseJson(String response, List<Media> arrayList) {
try {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(response);
JSONObject jsonObject = new JSONObject(String.valueOf(json));
JSONArray arrey = jsonObject.getJSONArray("result");
if (!media.getCustomMediaType().matches("آلبوم"))
arrayList.add(media);
for (int i = 0; i < arrey.length(); i++) {
JSONObject j = arrey.getJSONObject(i);
Media mdia = new Media(j);
if (!media.getId().matches(mdia.getId()) && !mdia.getCustomMediaType().matches("آلبوم"))
arrayList.add(mdia);
}
} catch (Exception e) {
}
if (mPlayerService != null) {
mPlayerService.setOnlineList(similarSongsList);
}
}
private VolleyRequestHelper.OnRequestCompletedListener requestCompletedListener =
new VolleyRequestHelper.OnRequestCompletedListener() {
#Override
public void onRequestCompleted(String requestName, boolean status,
String response, String errorMessage) {
//homeView.hideProgress();
switch (requestName) {
case "SIMILAR_SONGS":
if (status) {
parseJson(response, similarSongsList);
updateData();
}
break;
case "ALBUM_TRACKS":
if (status) {
parseJson(response, similarSongsList);
updateData();
if (initAlbum) {
setMedia(similarSongsList.get(0));
}
}
break;
}
}
};
//_______________________________________EXOPLAYER______________________________________________
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
if (checkChangeMediaDetails) {
musicChange(mPlayerService.getPlayingMedia());
} else checkChangeMediaDetails = true;
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if ((playbackState == Player.STATE_READY) && playWhenReady) {
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
}
} else if ((playbackState == Player.STATE_READY)) {
setPlayButton(false);
} else if (playbackState == Player.STATE_ENDED) {
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
//______________________________________________________________________________________________
public void setStartService() {
Intent intent = new Intent(this, PlayerService.class);
bindService(intent, this, Context.BIND_AUTO_CREATE);
startService(intent);
startService = true;
}
public void setStopService() {
Intent intentStop = new Intent(this, PlayerService.class);
stopService(intentStop);
}
public void setPlayButton(boolean playButton) {
mPlayPause.setPlayed(playButton);
mPlayPause.startAnimation();
}
public void setMusicInService(Media mMedia, int position) {
positionOfMusic = position;
if (mPlayerService != null) {
mPlayerService.setPlayMedia(mMedia, position);
} else {
setStartService();
setMedia(mMedia);
}
//positionOfMusic = position;
/*if (mPlayerService != null) {
mPlayerService.setMediaUri(mMedia.getStreamUrl());
mPlayerService.setMedia(mMedia);
mPlayerService.setPlayingMedia(position);
mPlayerService.preparePlayer();
} else {
positionOfMusic = position;
setStartService();
setMedia(mMedia);
}*/
}
public void musicChange(int newPosition) {
if (similarSongsList != null && similarSongsList.size() != 0) {
setMedia(similarSongsList.get(newPosition));
similarSongsAdapter.setPlayPosition(newPosition);
similarSongsAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
How to use SpeechRecognizer continuously without timeout. This is my code i am getting result on textview but this stops after listening few seconds. In my case i have to start until user don't stop it or it should stop after 15 to 20 minutes. if this is possible then please suggest me how to do. i want to increase timeout delay.
public class VoiceService extends Service {
String result;
private SpeechRecognizer sr;
class listener implements RecognitionListener {
listener() {
}
public void onReadyForSpeech(Bundle params) {
}
public void onBeginningOfSpeech() {Toast.makeText(VoiceService.this, "Listening", Toast.LENGTH_SHORT).show();}
public void onRmsChanged(float rmsdB) {
}
public void onBufferReceived(byte[] buffer) {
}
public void onEndOfSpeech() {
Toast.makeText(VoiceService.this, "Stopped", Toast.LENGTH_SHORT).show();
}
public void onError(int error) {
}
public void onResults(Bundle results) {
ArrayList<String> matches =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null){
FragmentTwo.textViewresult.setText(matches.get(0));}
}
public void onPartialResults(Bundle partialResults) {
}
public void onEvent(int eventType, Bundle params) {
}
}
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started",
Toast.LENGTH_SHORT).show();
AudioManager amanager = (AudioManager)
getSystemService("audio");
amanager.setStreamMute(3, true);
amanager.setStreamMute(1, true);
onClickk();
}
public void onDestroy() {
super.onDestroy();
if (this.sr != null) {
this.sr.destroy();
}
Toast.makeText(this, "Voice Service Stopped", Toast.LENGTH_SHORT).show();
}
public void onClickk() {
if (this.sr != null) {
this.sr.destroy();
}
this.sr = SpeechRecognizer.createSpeechRecognizer(this);
this.sr.setRecognitionListener(new listener());
Intent intent = new Intent("android.speech.action.RECOGNIZE_SPEECH");
intent.putExtra("android.speech.extra.LANGUAGE_MODEL", "free_form");
intent.putExtra("android.speech.extra.MAX_RESULTS", 1);
this.sr.startListening(intent);
}}
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void ListenForNewMessage()
{
final SpeechRecognizer newDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
newDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
if (newDeliverySpeech.isRecognitionAvailable(getApplicationContext()))
{
Log.d("SpeechListening","started listening hopefully");
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
}
}
The problem is, only the started listening hopefully is logged, the RecognitionListener never has onReadyForSpeech() or any of its methods called.
details
details
details
details
Can someone please tell me what I'm doing wrong here?
You are basically creating a new SpeechRecognizer object and register a new listener each time you click on the button. On top of that you create the SpeechRecognizer using the current Activity Context but you are actually using the Application context when calling: isRecognitionAvailable();
Try to create the SpeechRecognizer as a member object and register your listener when onCreate() is called. Also try to avoid using the Application context to avoid memory leaks.
Here is an example of how you should do it.
private SpeechRecognizer mDeliverySpeech;
private Intent mSpeechIntent;
private boolean mListening = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
SetupSpeechRecognizer();
mSpeechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void SetupSpeechRecognizer()
{
mDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
mDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
}
private void ListenForNewMessage()
{
if (mDeliverySpeech.isRecognitionAvailable(this) && !mListening)
{
Log.d("SpeechListening","started listening hopefully");
mListening = true;
mDeliverySpeech.startListening(mSpeechIntent);
new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
mDeliverySpeech.stopListening();
mListening = false;
}
}.start();
}
}
Do not forget to properly handle the activity life cycle when working with listener to avoid memory leak.
I have been successfully using YouTubePlayerSupportFragment to play YouTube videos.
But I still need to continue playing in the background, when the back button is pressed.
If you have any ideas, please share with me. Thanks!
Here is my code -
YoutubePlayerFragment class
public class YoutubePlayerFragment {
public static String DEVELOPER_KEY = "DEVELOPER_KEY";
public static boolean isFullScreen;
public static void setYoutubePlayerFragment(final Fragment fragment) {
MainFragment.youtubePlayerFragment = new YouTubePlayerSupportFragment();
MainFragment.youtubePlayerFragment.initialize(DEVELOPER_KEY, new OnInitializedListener() {
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
}
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer player,
boolean paramBoolean) {
PlayerService.youTubePlayer = player;
PlayerService.youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
setListener(fragment.getActivity());
}
});
replaceFragment(fragment);
}
public static void replaceFragment(final Fragment fragment) {
if (fragment == null)
return;
FragmentManager fragmentManager = fragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.youtubeplayerFrameLayout,
MainFragment.youtubePlayerFragment);
fragmentTransaction.commit();
}
public static void setListener(final Activity activity) {
PlayerService.youTubePlayer.setOnFullscreenListener(new OnFullscreenListener() {
#Override
public void onFullscreen(boolean isFullScreen) {
YoutubePlayerFragment.isFullScreen = isFullScreen;
Log.d(App.tagName, "setOnFullscreenListener : onFullscreen");
}
});
PlayerService.youTubePlayer.setPlayerStateChangeListener(new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
Log.d(App.tagName, "setPlayerStateChangeListener : onAdStarted");
}
#Override
public void onError(ErrorReason arg0) {
Log.d(App.tagName, "setPlayerStateChangeListener : onError : " + arg0);
}
#Override
public void onLoaded(String arg0) {
Log.d(App.tagName, "setPlayerStateChangeListener : onLoaded");
}
#Override
public void onLoading() {
Log.d(App.tagName, "setPlayerStateChangeListener : onLoading");
}
#Override
public void onVideoEnded() {
Log.d(App.tagName, "setPlayerStateChangeListener : onVideoEnded");
}
#Override
public void onVideoStarted() {
Log.d(App.tagName, "setPlayerStateChangeListener : onVideoStarted");
}
});
PlayerService.youTubePlayer.setPlaybackEventListener(new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
Log.d(App.tagName, "setPlaybackEventListener : onBuffering");
if (MainActivity.isBack && PlayerService.youTubePlayer != null) {
PlayerService.youTubePlayer.play();
}
}
#Override
public void onPaused() {
Log.d(App.tagName, "setPlaybackEventListener : onPaused");
PlayerFrameLayout.ibPlay.setImageResource(R.drawable.ic_play_arrow_white_36dp);
if (MainActivity.isBack && PlayerService.youTubePlayer != null) {
PlayerService.youTubePlayer.play();
}
}
#Override
public void onPlaying() {
Log.d(App.tagName, "setPlaybackEventListener : onPlaying");
PlayerFrameLayout.ibPlay.setImageResource(R.drawable.ic_pause_white_36dp);
}
#Override
public void onSeekTo(int arg0) {
Log.d(App.tagName, "setPlaybackEventListener : onSeekTo");
}
#Override
public void onStopped() {
Log.d(App.tagName, "setPlaybackEventListener : onStopped");
}
});
}}
Using Service to play Youtube video.
public class PlayerService extends Service {
public static YouTubePlayer youTubePlayer = null;
private int MSG;
#Override
public void onCreate() {
super.onCreate();
Log.d(App.tagName, "PlayerService : onCreate");
YoutubePlayerFragment.setYoutubePlayerFragment(MainFragment.mainFragment);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(App.tagName, "PlayerService : onStartCommand");
MediaInfo mediaInfo = MusicListFragment.getCurrentMp3Info();
youTubePlayer.loadVideo(mediaInfo.video_id);
youTubePlayer.play();
return super.onStartCommand(intent, flags, startId);
} }