Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PodcastPlaybackService.java « services « owncloudnewsreader « luhmer « de « java « main « src « News-Android-App - github.com/nextcloud/news-android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 503cb356644431aeeb0459a5eaaded2825dab681 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package de.luhmer.owncloudnewsreader.services;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Toast;

import java.io.IOException;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import de.luhmer.owncloudnewsreader.R;
import de.luhmer.owncloudnewsreader.events.podcast.NewPodcastPlaybackListener;
import de.luhmer.owncloudnewsreader.events.podcast.PodcastCompletedEvent;
import de.luhmer.owncloudnewsreader.events.podcast.RegisterVideoOutput;
import de.luhmer.owncloudnewsreader.events.podcast.TogglePlayerStateEvent;
import de.luhmer.owncloudnewsreader.events.podcast.UpdatePodcastStatusEvent;
import de.luhmer.owncloudnewsreader.events.podcast.WindPodcast;
import de.luhmer.owncloudnewsreader.model.PodcastItem;
import de.luhmer.owncloudnewsreader.model.TTSItem;
import de.luhmer.owncloudnewsreader.view.PodcastNotification;

public class PodcastPlaybackService extends Service implements TextToSpeech.OnInitListener {

    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();

    public PodcastItem getCurrentlyPlayingPodcast() {
        return mCurrentlyPlayingPodcast;
    }

    public boolean isActive() {
        return mCurrentlyPlayingPodcast != null || mCurrentlyPlayingTTS != null;
    }

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        public PodcastPlaybackService getService() {
            // Return this instance of LocalService so clients can call public methods
            return PodcastPlaybackService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (!isActive()) {
            Log.v(TAG, "Stopping PodcastPlaybackService because of inactivity");
            stopSelf();
        }

        podcastNotification.unbind();

        return super.onUnbind(intent);
    }

    public static final String PODCAST_ITEM = "PODCAST_ITEM";
    public static final String TTS_ITEM = "TTS_ITEM";

    private PodcastItem mCurrentlyPlayingPodcast;
    private TTSItem mCurrentlyPlayingTTS;

    private static final String TAG = "PodcastPlaybackService";
    private PodcastNotification podcastNotification;

    private EventBus eventBus;
    private Handler mHandler;
    private MediaPlayer mMediaPlayer;


    private TextToSpeech ttsController;
    private String mediaTitle;
    private PlaybackType mPlaybackType;
    private View parentResizableView;

    private enum PlaybackType { PODCAST, TTS }

    @Override
    public void onCreate() {
        Log.v(TAG, "onCreate PodcastPlaybackService");

        mediaTitle = getString(R.string.no_podcast_selected);

        TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if(mgr != null) {
            mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }

        mMediaPlayer = new MediaPlayer();
        podcastNotification = new PodcastNotification(this);
        mHandler = new Handler();
        eventBus = EventBus.getDefault();

        eventBus.register(this);

        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
                isPreparing = false;
                Toast.makeText(PodcastPlaybackService.this, "Failed to open podcast", Toast.LENGTH_LONG).show();
                return false;
            }
        });

        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                play();
                isPreparing = false;
                canCallGetDuration = true;
            }
        });

        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                pause();//Send the over signal
                podcastCompleted();
            }
        });


        eventBus.post(new PodcastPlaybackServiceStarted());

        mHandler.postDelayed(mUpdateTimeTask, 0);

        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.v(TAG, "onDestroy PodcastPlaybackService");

        TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mgr != null) {
            mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
        }

        podcastNotification.cancel();

        super.onDestroy();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            if (intent.hasExtra(PODCAST_ITEM)) {
                openFile((PodcastItem) intent.getSerializableExtra(PODCAST_ITEM));
            } else if(intent.hasExtra(TTS_ITEM)) {
                openTtsFeed((TTSItem) intent.getSerializableExtra(TTS_ITEM));
            }
        }

        return Service.START_STICKY;
    }


    public static final int delay = 500; //In milliseconds

    private boolean canCallGetDuration = false;//Otherwise the player would call getDuration all the time without loading a media file
    private boolean isPreparing = false;
    private boolean isVideoFile = false;

    public void openTtsFeed(TTSItem textToSpeechItem) {
        this.mCurrentlyPlayingTTS = textToSpeechItem;
        this.mCurrentlyPlayingPodcast = null;

        this.mPlaybackType = PlaybackType.TTS;
        this.isVideoFile = false;

        try {
            if(mMediaPlayer.isPlaying())
                pause();

            this.mediaTitle = textToSpeechItem.title;

            isPreparing = true;
            mHandler.postDelayed(mUpdateTimeTask, 0);

            if(ttsController == null) {
                ttsController = new TextToSpeech(this, this);
                ttsController.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                    @Override
                    public void onDone(String utteranceId) {
                        podcastCompleted();
                    }

                    @Override public void onStart(String utteranceId) {}
                    @Override public void onError(String utteranceId) {}
                });
            }
            else
                onInit(TextToSpeech.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void podcastCompleted() {
        Log.d(TAG, "Podcast completed, cleaning up");
        mHandler.removeCallbacks(mUpdateTimeTask);
        podcastNotification.cancel();
        mCurrentlyPlayingPodcast = null;
        mCurrentlyPlayingTTS = null;

        EventBus.getDefault().post(new PodcastCompletedEvent());
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            /*
            int result = ttsController.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            } else {
                ttsController.speak(text, TextToSpeech.QUEUE_FLUSH, null);
            }*/

            HashMap<String,String> ttsParams = new HashMap<>();
            ttsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"dummyId");
            ttsController.speak(mCurrentlyPlayingTTS.text, TextToSpeech.QUEUE_FLUSH, ttsParams);

            isPreparing = false;

        } else {
            Log.e("TTS", "Initilization Failed!");
            ttsController = null;
        }
    }

    public void openFile(PodcastItem podcastItem) {
        this.mPlaybackType = PlaybackType.PODCAST;
        this.mCurrentlyPlayingPodcast = podcastItem;
        this.mCurrentlyPlayingTTS = null;

        this.isVideoFile = podcastItem.isVideoPodcast;
        try {
            if(mMediaPlayer.isPlaying())
                pause();

            this.mediaTitle = podcastItem.title;

            isPreparing = true;
            mHandler.postDelayed(mUpdateTimeTask, 0);

            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(podcastItem.link);
            mMediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            isPreparing = false;
        }

        podcastNotification.podcastChanged();
    }

    /**
     * Background Runnable thread
     * */
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            sendMediaStatus();

            mHandler.postDelayed(this, delay);
        }
    };

    public void onEvent(TogglePlayerStateEvent event) {
        if (isPlaying()) {
            Log.v(TAG, "calling pause()");
            pause();
        } else {
            Log.v(TAG, "calling play()");
            play();
        }
    }

    private boolean isPlaying() {
        return (mPlaybackType == PlaybackType.PODCAST && mMediaPlayer.isPlaying()) || //If podcast is running
                mPlaybackType == PlaybackType.TTS && ttsController.isSpeaking(); // or if tts is running
    }

    public void onEvent(WindPodcast event) {
        if(mMediaPlayer != null) {
            double totalDuration = mMediaPlayer.getDuration();
            int position = (int)((totalDuration / 100d) * event.toPositionInPercent);
            mMediaPlayer.seekTo(position);
        }
    }

    /*
    public void onEventBackgroundThread(OpenPodcastEvent event) {
        this.isVideoFile = event.isVideoFile;
        openFile(event.pathToFile, event.mediaTitle);
    }
    */

    public void onEvent(RegisterVideoOutput videoOutput) {
        if(mMediaPlayer != null) {
            if(videoOutput.surfaceView == null) {
                mMediaPlayer.setDisplay(null);
                Log.d(TAG, "Disable Screen output!");

                mMediaPlayer.setScreenOnWhilePlaying(false);
            } else {
                if(videoOutput.surfaceView.getHolder() != mSurfaceHolder) {
                    parentResizableView = videoOutput.parentResizableView;

                    videoOutput.surfaceView.getHolder().addCallback(mSHCallback);
                    //videoOutput.surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);

                    populateVideo();

                    Log.d(TAG, "Enable Screen output!");
                }
            }
        }
    }

    public void onEvent(NewPodcastPlaybackListener newListener) {
        sendMediaStatus();
    }




    public void play() {
        if(mPlaybackType == PlaybackType.PODCAST) {
            try {
                int progress = mMediaPlayer.getCurrentPosition() / mMediaPlayer.getDuration();
                if (progress >= 1) {
                    mMediaPlayer.seekTo(0);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            mMediaPlayer.start();
        } else {
            onInit(TextToSpeech.SUCCESS);//restart last tts
        }

        mHandler.removeCallbacks(mUpdateTimeTask);
        mHandler.postDelayed(mUpdateTimeTask, 0);

        populateVideo();
    }

    private void populateVideo() {
        double videoHeightRel = (double) mSurfaceWidth / (double) mMediaPlayer.getVideoWidth();
        int videoHeight = (int) (mMediaPlayer.getVideoHeight() * videoHeightRel);

        if (mSurfaceWidth != 0 && videoHeight != 0 && mSurfaceHolder != null) {
            //mSurfaceHolder.setFixedSize(mSurfaceWidth, videoHeight);

            parentResizableView.getLayoutParams().height = videoHeight;
            parentResizableView.setLayoutParams(parentResizableView.getLayoutParams());
        }
    }

    public void pause() {
        if(mPlaybackType == PlaybackType.PODCAST) {
            if (mMediaPlayer.isPlaying())
                mMediaPlayer.pause();
        }

        if(mPlaybackType == PlaybackType.TTS) {
            if (ttsController.isSpeaking()) {
                ttsController.stop();

                //The tts service needs a few ms's to end playing. So wait 100ms
                try {
                    Thread.sleep(100);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        mHandler.removeCallbacks(mUpdateTimeTask);
        sendMediaStatus();
    }

    public void sendMediaStatus() {
        long totalDuration = 0;
        long currentDuration = 0;

        if(mPlaybackType == PlaybackType.PODCAST) {
            if (!isPreparing && canCallGetDuration) {
                totalDuration = mMediaPlayer.getDuration();
                currentDuration = mMediaPlayer.getCurrentPosition();
            }

            long currentRssItemId = -1;
            if (mCurrentlyPlayingPodcast != null)
                currentRssItemId = mCurrentlyPlayingPodcast.itemId;

            UpdatePodcastStatusEvent audioPodcastEvent = new UpdatePodcastStatusEvent(currentDuration, totalDuration, mMediaPlayer.isPlaying(), mediaTitle, isPreparing, canCallGetDuration, isVideoFile, currentRssItemId);
            eventBus.post(audioPodcastEvent);
        } else if(mPlaybackType == PlaybackType.TTS) {
            UpdatePodcastStatusEvent audioPodcastEvent = new UpdatePodcastStatusEvent(0, 0, ttsController.isSpeaking(), mediaTitle, isPreparing, true, false, mCurrentlyPlayingTTS.itemId);
            eventBus.post(audioPodcastEvent);
        }
    }


    public class PodcastPlaybackServiceStarted {

    }

    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            if (state == TelephonyManager.CALL_STATE_RINGING) {
                //Incoming call: Pause music
                pause();
            } else if(state == TelephonyManager.CALL_STATE_IDLE) {
                //Not in call: Play music
            } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
                //A call is dialing, active or on hold
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };




    int mSurfaceWidth;
    int mSurfaceHeight;
    SurfaceHolder mSurfaceHolder;
    SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback()
    {
        public void surfaceChanged(SurfaceHolder holder, int format, int surfaceWidth, int surfaceHeight)
        {
            mSurfaceWidth = surfaceWidth;
            mSurfaceHeight = surfaceHeight;
        }

        public void surfaceCreated(SurfaceHolder holder)
        {
            mSurfaceHolder = holder;
            mMediaPlayer.setDisplay(mSurfaceHolder);

            mMediaPlayer.setScreenOnWhilePlaying(true);

            Log.d(TAG, "surfaceCreated");
        }

        public void surfaceDestroyed(SurfaceHolder holder)
        {
            Log.d(TAG, "surfaceDestroyed");
        }
    };
}