This repository has been archived by the owner on Nov 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 772
/
FolioReaderAudioPlayer.swift
523 lines (423 loc) · 16.1 KB
/
FolioReaderAudioPlayer.swift
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//
// FolioReaderAudioPlayer.swift
// FolioReaderKit
//
// Created by Kevin Jantzer on 1/4/16.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
class FolioReaderAudioPlayer: NSObject {
var isTextToSpeech = false
var synthesizer: AVSpeechSynthesizer!
var playing = false
var player: AVAudioPlayer?
var currentHref: String!
var currentFragment: String!
var currentSmilFile: FRSmilFile!
var currentAudioFile: String!
var currentBeginTime: Double!
var currentEndTime: Double!
var playingTimer: NSTimer!
var registeredCommands = false
var completionHandler: () -> Void = {}
var utteranceRate: Float = 0
// MARK: Init
override init() {
super.init()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
// this is needed to the audio can play even when the "silent/vibrate" toggle is on
let session:AVAudioSession = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayback)
try! session.setActive(true)
updateNowPlayingInfo()
}
deinit {
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
}
// MARK: Reading speed
func setRate(rate: Int) {
if let player = player {
switch rate {
case 0:
player.rate = 0.5
break
case 1:
player.rate = 1.0
break
case 2:
player.rate = 1.5
break
case 3:
player.rate = 2
break
default:
break
}
updateNowPlayingInfo()
}
if synthesizer != nil {
// Need to change between version IOS
// http://stackoverflow.com/questions/32761786/ios9-avspeechutterance-rate-for-avspeechsynthesizer-issue
if #available(iOS 9, *) {
switch rate {
case 0:
utteranceRate = 0.42
break
case 1:
utteranceRate = 0.5
break
case 2:
utteranceRate = 0.53
break
case 3:
utteranceRate = 0.56
break
default:
break
}
} else {
switch rate {
case 0:
utteranceRate = 0
break
case 1:
utteranceRate = 0.06
break
case 2:
utteranceRate = 0.15
break
case 3:
utteranceRate = 0.23
break
default:
break
}
}
updateNowPlayingInfo()
}
}
// MARK: Play, Pause, Stop controls
func stop(immediate immediate: Bool = false) {
playing = false
if !isTextToSpeech {
if let player = player where player.playing {
player.stop()
}
} else {
stopSynthesizer(immediate: immediate, completion: nil)
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
func stopSynthesizer(immediate immediate: Bool = false, completion: (() -> Void)? = nil) {
synthesizer.stopSpeakingAtBoundary(immediate ? .Immediate : .Word)
completion?()
}
func pause() {
playing = false
if !isTextToSpeech {
if let player = player where player.playing {
player.pause()
}
} else {
if synthesizer.speaking {
synthesizer.pauseSpeakingAtBoundary(.Word)
}
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
func togglePlay() {
isPlaying() ? pause() : play()
}
func play() {
if book.hasAudio() {
guard let currentPage = FolioReader.sharedInstance.readerCenter.currentPage else { return }
currentPage.webView.js("playAudio()")
} else {
readCurrentSentence()
}
// UIApplication.sharedApplication().idleTimerDisabled = true
}
func isPlaying() -> Bool {
return playing
}
/**
Play Audio (href/fragmentID)
Begins to play audio for the given chapter (href) and text fragment.
If this chapter does not have audio, it will delay for a second, then attempt to play the next chapter
*/
func playAudio(href: String, fragmentID: String) {
isTextToSpeech = false
stop()
let smilFile = book.smilFileForHref(href)
// if no smil file for this href and the same href is being requested, we've hit the end. stop playing
if smilFile == nil && currentHref != nil && href == currentHref {
return
}
playing = true
currentHref = href
currentFragment = "#"+fragmentID
currentSmilFile = smilFile
// if no smil file, delay for a second, then move on to the next chapter
if smilFile == nil {
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(_autoPlayNextChapter), userInfo: nil, repeats: false)
return
}
let fragment = smilFile.parallelAudioForFragment(currentFragment)
if fragment != nil {
if _playFragment(fragment) {
startPlayerTimer()
}
}
}
func _autoPlayNextChapter() {
// if user has stopped playing, dont play the next chapter
if isPlaying() == false { return }
playNextChapter()
}
func playPrevChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter.changePageToPrevious {
if self.isPlaying() {
self.play()
} else {
self.pause()
}
}
}
func playNextChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter.changePageToNext {
if self.isPlaying() {
self.play()
}
}
}
/**
Play Fragment of audio
Once an audio fragment begins playing, the audio clip will continue playing until the player timer detects
the audio is out of the fragment timeframe.
*/
private func _playFragment(smil: FRSmilElement!) -> Bool {
if smil == nil {
print("no more parallel audio to play")
stop()
return false
}
let textFragment = smil.textElement().attributes["src"]
let audioFile = smil.audioElement().attributes["src"]
currentBeginTime = smil.clipBegin()
currentEndTime = smil.clipEnd()
// new audio file to play, create the audio player
if player == nil || (audioFile != nil && audioFile != currentAudioFile) {
currentAudioFile = audioFile
let fileURL = currentSmilFile.resource.basePath().stringByAppendingString("/"+audioFile!)
let audioData = NSData(contentsOfFile: fileURL)
do {
player = try AVAudioPlayer(data: audioData!)
guard let player = player else { return false }
setRate(FolioReader.currentAudioRate)
player.enableRate = true
player.prepareToPlay()
player.delegate = self
updateNowPlayingInfo()
} catch {
print("could not read audio file:", audioFile)
return false
}
}
// if player is initialized properly, begin playing
guard let player = player else { return false }
// the audio may be playing already, so only set the player time if it is NOT already within the fragment timeframe
// this is done to mitigate milisecond skips in the audio when changing fragments
if player.currentTime < currentBeginTime || ( currentEndTime > 0 && player.currentTime > currentEndTime) {
player.currentTime = currentBeginTime;
updateNowPlayingInfo()
}
player.play()
// get the fragment ID so we can "mark" it in the webview
let textParts = textFragment!.componentsSeparatedByString("#")
let fragmentID = textParts[1];
FolioReader.sharedInstance.readerCenter.audioMark(href: currentHref, fragmentID: fragmentID)
return true
}
/**
Next Audio Fragment
Gets the next audio fragment in the current smil file, or moves on to the next smil file
*/
private func nextAudioFragment() -> FRSmilElement! {
let smilFile = book.smilFileForHref(currentHref)
if smilFile == nil { return nil }
let smil = currentFragment == nil ? smilFile.parallelAudioForFragment(nil) : smilFile.nextParallelAudioForFragment(currentFragment)
if smil != nil {
currentFragment = smil.textElement().attributes["src"]
return smil
}
currentHref = book.spine.nextChapter(currentHref)!.href
currentFragment = nil
currentSmilFile = smilFile
if currentHref == nil {
return nil
}
return nextAudioFragment()
}
func playText(href: String, text: String) {
isTextToSpeech = true
playing = true
currentHref = href
if synthesizer == nil {
synthesizer = AVSpeechSynthesizer()
synthesizer.delegate = self
setRate(FolioReader.currentAudioRate)
}
let utterance = AVSpeechUtterance(string: text)
utterance.rate = utteranceRate
utterance.voice = AVSpeechSynthesisVoice(language: book.metadata.language)
if synthesizer.speaking {
stopSynthesizer()
}
synthesizer.speakUtterance(utterance)
updateNowPlayingInfo()
}
// MARK: TTS Sentence
func speakSentence() {
guard let currentPage = FolioReader.sharedInstance.readerCenter.currentPage else { return }
let sentence = currentPage.webView.js("getSentenceWithIndex('\(book.playbackActiveClass())')")
if sentence != nil {
let chapter = FolioReader.sharedInstance.readerCenter.getCurrentChapter()
let href = chapter != nil ? chapter!.href : "";
playText(href, text: sentence!)
} else {
if FolioReader.sharedInstance.readerCenter.isLastPage() {
stop()
} else {
FolioReader.sharedInstance.readerCenter.changePageToNext()
}
}
}
func readCurrentSentence() {
guard synthesizer != nil else { return speakSentence() }
if synthesizer.paused {
playing = true
synthesizer.continueSpeaking()
} else {
if synthesizer.speaking {
stopSynthesizer(immediate: false, completion: {
if let currentPage = FolioReader.sharedInstance.readerCenter.currentPage {
currentPage.webView.js("resetCurrentSentenceIndex()")
}
self.speakSentence()
})
} else {
speakSentence()
}
}
}
// MARK: - Audio timing events
private func startPlayerTimer() {
// we must add the timer in this mode in order for it to continue working even when the user is scrolling a webview
playingTimer = NSTimer(timeInterval: 0.01, target: self, selector: #selector(playerTimerObserver), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(playingTimer, forMode: NSRunLoopCommonModes)
}
private func stopPlayerTimer() {
if playingTimer != nil {
playingTimer.invalidate()
playingTimer = nil
}
}
func playerTimerObserver() {
guard let player = player else { return }
if currentEndTime != nil && currentEndTime > 0 && player.currentTime > currentEndTime {
_playFragment(nextAudioFragment())
}
}
// MARK: - Now Playing Info and Controls
/**
Update Now Playing info
Gets the book and audio information and updates on Now Playing Center
*/
func updateNowPlayingInfo() {
var songInfo = [String: AnyObject]()
// Get book Artwork
if let coverImage = book.coverImage, let artwork = UIImage(contentsOfFile: coverImage.fullHref) {
let albumArt = MPMediaItemArtwork(image: artwork)
songInfo[MPMediaItemPropertyArtwork] = albumArt
}
// Get book title
if let title = book.title() {
songInfo[MPMediaItemPropertyAlbumTitle] = title
}
// Get chapter name
if let chapter = getCurrentChapterName() {
songInfo[MPMediaItemPropertyTitle] = chapter
}
// Get author name
if let author = book.metadata.creators.first {
songInfo[MPMediaItemPropertyArtist] = author.name
}
// Set player times
if let player = player where !isTextToSpeech {
songInfo[MPMediaItemPropertyPlaybackDuration] = player.duration
songInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
songInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime ] = player.currentTime
}
// Set Audio Player info
MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo
registerCommandsIfNeeded()
}
/**
Get Current Chapter Name
This is done here and not in ReaderCenter because even though `currentHref` is accurate,
the `currentPage` in ReaderCenter may not have updated just yet
*/
func getCurrentChapterName() -> String? {
guard let chapter = FolioReader.sharedInstance.readerCenter.getCurrentChapter() else {
return nil
}
currentHref = chapter.href
for item in book.flatTableOfContents {
if let resource = item.resource where resource.href == currentHref {
return item.title
}
}
return nil
}
/**
Register commands if needed, check if it's registered to avoid register twice.
*/
func registerCommandsIfNeeded() {
guard !registeredCommands else { return }
let command = MPRemoteCommandCenter.sharedCommandCenter()
command.previousTrackCommand.enabled = true
command.previousTrackCommand.addTarget(self, action: #selector(playPrevChapter))
command.nextTrackCommand.enabled = true
command.nextTrackCommand.addTarget(self, action: #selector(playNextChapter))
command.pauseCommand.enabled = true
command.pauseCommand.addTarget(self, action: #selector(pause))
command.playCommand.enabled = true
command.playCommand.addTarget(self, action: #selector(play))
command.togglePlayPauseCommand.enabled = true
command.togglePlayPauseCommand.addTarget(self, action: #selector(togglePlay))
registeredCommands = true
}
}
// MARK: AVSpeechSynthesizerDelegate
extension FolioReaderAudioPlayer: AVSpeechSynthesizerDelegate {
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didCancelSpeechUtterance utterance: AVSpeechUtterance) {
completionHandler()
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
if isPlaying() {
readCurrentSentence()
}
}
}
// MARK: AVAudioPlayerDelegate
extension FolioReaderAudioPlayer: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
_playFragment(nextAudioFragment())
}
}