Compare commits

...

25 Commits

Author SHA1 Message Date
Tanha c325caa914 Release 2.9.0 2020-03-06 23:53:42 -08:00
tanhakabir dd54d81573 implement streaming cancellation (#32)
* cancels streaming initally, but player enters weird state trying to stream again

* calling superclass invalidate from engines for good measure

* Fix UI to fix seemingly weird state

* Fix error warning
2020-03-06 23:52:22 -08:00
tanhakabir ebc282d5c2 fix crash on cancel streaming pressed (#30) 2020-03-06 23:28:30 -08:00
Tanha 80ce253f92 Release 2.8.2 2020-01-21 00:29:28 -08:00
tanhakabir fe2395066f Add equalizer example (#28)
* project configure for me

* to see log

* set project

* new UI

* fix ui

* re-fix UI

* add example of equalizer

* Revert "re-fix UI"

This reverts commit 05ed993a52.

* Revert "fix ui"

This reverts commit 0da9f6adea.

* Revert "new UI"

This reverts commit ffd6a95a2d.

* Add verbose debug mode to player

Co-authored-by: cendolinside123 <jnsbstn391@gmail.com>
2020-01-21 00:27:51 -08:00
Tanha 3e66b4b4d4 Release 2.8.1 2020-01-04 13:35:29 -08:00
Tanha 58bbc97a1b Minor fix on end of audio notification 2020-01-04 13:35:03 -08:00
Tanha 8d9e9d92f4 Release 2.8.0 2020-01-04 13:24:47 -08:00
tanhakabir 03392c21e0 fix bug in notification of end of audio in PlayingStatus (#25) 2020-01-04 13:23:50 -08:00
Tanha 924170d159 Release 2.7.0 2020-01-04 02:04:35 -08:00
tanhakabir b355eb4e09 add api for buffer progress in SAAvailabilityRange (#24) 2020-01-04 02:02:56 -08:00
Tanha 1373a816a6 Release 2.6.0 2019-12-18 21:23:07 -08:00
tanhakabir 196b04a703 Rename and deprecate initialize functions (#23) 2019-12-18 21:22:28 -08:00
Tanha ac971e65a6 Release 2.5.2 2019-12-18 16:19:57 -08:00
Tanha 2c50502b28 update documentation for live streaming audio 2019-12-18 16:19:37 -08:00
Tanha c222b5a745 Release 2.5.1 2019-12-18 00:27:49 -08:00
Tanha 2e86a6503c Clean up debug logging 2019-12-18 00:27:21 -08:00
Tanha 9ebd7fa7fe Release 2.5.0 2019-12-18 00:24:11 -08:00
tanhakabir 5197a16023 Fix live streams/servers with unpredictable size at beginning of stream being playable (#21)
* Handle case when header for stream does not contain expected content

* update documentation

* fix elapsed time updating on seek in example app
2019-12-18 00:22:31 -08:00
Tanha 159627c63e Release 2.4.0 2019-12-03 01:43:45 -08:00
tanhakabir 07230cce1a add another status to PlayingStatus for end of audio (#19) 2019-12-03 01:42:56 -08:00
tanhakabir a33aee80d1 Expose engine outside of SAPlayer (#18)
* expose engine outside of player

* add player clearing functionality
2019-12-03 01:25:58 -08:00
tanhakabir e1d3da1ddb Update README.md 2019-12-01 11:10:12 -08:00
Tanha 8c2524d990 Release 2.3.0 2019-12-01 01:17:54 -08:00
Tanha be1b7aa05f fix bug on bad network and streaming being stuck in missing data state
close #4
2019-12-01 01:16:03 -08:00
19 changed files with 277 additions and 82 deletions
@@ -212,12 +212,12 @@
TargetAttributes = {
607FACCF1AFB9204008FA782 = {
CreatedOnToolsVersion = 6.3.1;
DevelopmentTeam = R2392A68YQ;
DevelopmentTeam = H9Y26B6GZB;
LastSwiftMigration = 1120;
};
607FACE41AFB9204008FA782 = {
CreatedOnToolsVersion = 6.3.1;
DevelopmentTeam = R2392A68YQ;
DevelopmentTeam = H9Y26B6GZB;
LastSwiftMigration = 1120;
TestTargetID = 607FACCF1AFB9204008FA782;
};
@@ -475,11 +475,11 @@
baseConfigurationReference = 65A66AB4C3016E8BB53FF3E0 /* Pods-SwiftAudioPlayer_Example.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
DEVELOPMENT_TEAM = R2392A68YQ;
DEVELOPMENT_TEAM = H9Y26B6GZB;
INFOPLIST_FILE = SwiftAudioPlayer/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MODULE_NAME = ExampleApp;
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo-test.SwiftAudioPlayer-Example";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
@@ -490,11 +490,11 @@
baseConfigurationReference = 4B5DD2AE0B23A759D18926DC /* Pods-SwiftAudioPlayer_Example.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
DEVELOPMENT_TEAM = R2392A68YQ;
DEVELOPMENT_TEAM = H9Y26B6GZB;
INFOPLIST_FILE = SwiftAudioPlayer/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MODULE_NAME = ExampleApp;
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo-test.SwiftAudioPlayer-Example";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
@@ -504,7 +504,7 @@
isa = XCBuildConfiguration;
baseConfigurationReference = BBD877782CC67FBCC7BF7532 /* Pods-SwiftAudioPlayer_Tests.debug.xcconfig */;
buildSettings = {
DEVELOPMENT_TEAM = R2392A68YQ;
DEVELOPMENT_TEAM = H9Y26B6GZB;
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
@@ -526,7 +526,7 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 0B7D1E6C00E83B4AF8AA1781 /* Pods-SwiftAudioPlayer_Tests.release.xcconfig */;
buildSettings = {
DEVELOPMENT_TEAM = R2392A68YQ;
DEVELOPMENT_TEAM = H9Y26B6GZB;
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
+41 -9
View File
@@ -59,7 +59,7 @@ class ViewController: UIViewController {
self.currentUrlLocationLabel.text = "remote url: \(selectedAudio.url.absoluteString)"
}
}
var freq:[Int] = [0,0,0,0,0,0,0,0,0,0]
@IBOutlet weak var currentUrlLocationLabel: UILabel!
@IBOutlet weak var bufferProgress: UIProgressView!
@IBOutlet weak var scrubberSlider: UISlider!
@@ -103,6 +103,8 @@ class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
SAPlayer.shared.DEBUG_MODE = true
isPlayable = false
selectedAudio = AudioInfo(index: 0)
@@ -117,7 +119,6 @@ class ViewController: UIViewController {
_ = SAPlayer.Updates.ElapsedTime.subscribe { [weak self] (url, position) in
guard let self = self else { return }
guard self.beingSeeked == false else { return }
guard url == self.selectedAudio.url || url == self.savedUrls[self.selectedAudio] else { return }
self.currentTimestampLabel.text = SAPlayer.prettifyTimestamp(position)
@@ -146,12 +147,12 @@ class ViewController: UIViewController {
if self.duration == 0.0 { return }
let progress = Float((buffer.totalDurationBuffered + buffer.startingBufferTimePositon) / self.duration)
self.bufferProgress.progress = Float(buffer.bufferingProgress)
self.bufferProgress.progress = progress
if progress >= 0.99 {
if buffer.bufferingProgress >= 0.99 {
self.streamButton.isEnabled = false
} else {
self.streamButton.isEnabled = true
}
self.isPlayable = buffer.isReadyForPlaying
@@ -174,6 +175,10 @@ class ViewController: UIViewController {
self.isPlayable = false
self.playPauseButton.setTitle("Loading", for: .normal)
return
case .ended:
self.isPlayable = false
self.playPauseButton.setTitle("Done", for: .normal)
return
}
}
}
@@ -182,6 +187,16 @@ class ViewController: UIViewController {
let node = AVAudioUnitReverb()
SAPlayer.shared.audioModifiers.append(node)
node.wetDryMix = 300
let frequency:[Int] = [60,170,310,600,1000,3000,6000,12000,14000,16000]
let node2 = AVAudioUnitEQ(numberOfBands:frequency.count)
node2.globalGain = 1
for i in 0...(node2.bands.count-1) {
node2.bands[i].frequency = Float(frequency[i])
node2.bands[i].gain = 0
node2.bands[i].bypass = false
node2.bands[i].filterType = .parametric
}
SAPlayer.shared.audioModifiers.append(node2)
}
override func didReceiveMemoryWarning() {
@@ -241,7 +256,7 @@ class ViewController: UIViewController {
self.currentUrlLocationLabel.text = "saved to: \(url.lastPathComponent)"
self.savedUrls[self.selectedAudio] = url
SAPlayer.shared.initializeSavedAudio(withSavedUrl: url)
SAPlayer.shared.startSavedAudio(withSavedUrl: url)
}
})
streamButton.isEnabled = false
@@ -256,11 +271,15 @@ class ViewController: UIViewController {
@IBAction func streamTouched(_ sender: Any) {
if !isStreaming {
SAPlayer.shared.initializeRemoteAudio(withRemoteUrl: selectedAudio.url)
SAPlayer.shared.startRemoteAudio(withRemoteUrl: selectedAudio.url)
streamButton.setTitle("Cancel streaming", for: .normal)
downloadButton.isEnabled = false
isStreaming = true
} else {
// TODO
SAPlayer.shared.stopStreamingRemoteAudio()
streamButton.setTitle("Stream", for: .normal)
downloadButton.isEnabled = true
isStreaming = false
}
}
@@ -275,6 +294,19 @@ class ViewController: UIViewController {
@IBAction func skipForwardTouched(_ sender: Any) {
SAPlayer.shared.skipForward()
}
@IBAction func setEqualizerValue(_ sender: Any) {
if let slider = sender as? UISlider{
print("slider of index:", slider.tag, "is changed to", slider.value)
freq[slider.tag] = Int(slider.value)
print("current frequency : ",freq)
if let node = SAPlayer.shared.audioModifiers[2] as? AVAudioUnitEQ{
for i in 0...(node.bands.count - 1){
node.bands[i].gain = Float(freq[i])
}
}
}
}
}
+6 -6
View File
@@ -20,8 +20,8 @@ iOS 10.0 and higher.
1. Clone repo
2. CD to directory
3. run `pod install` in terminal
4. Run
3. Run `pod install` in terminal
4. Build and run
### Installation
@@ -39,7 +39,7 @@ pod 'SwiftAudioPlayer'
To play remote audio:
```swift
let url = URL(string: "https://randomwebsite.com/audio.mp3")!
SAPlayer.shared.initializeAudio(withRemoteUrl: url)
SAPlayer.shared.startRemoteAudio(withRemoteUrl: url)
SAPlayer.shared.play()
```
@@ -121,8 +121,8 @@ Access the player and all of its fields and functions through `SAPlayer.shared`.
### Playing Audio (Basic Commands)
To set up player with audio to play, use either:
* `initializeSavedAudio(withSavedUrl url: URL, mediaInfo: SALockScreenInfo?)` to play audio that is saved on the device.
* `initializeRemoteAudio(withRemoteUrl url: URL, mediaInfo: SALockScreenInfo?)` to play audio streamed from a remote location.
* `startSavedAudio(withSavedUrl url: URL, mediaInfo: SALockScreenInfo?)` to play audio that is saved on the device.
* `startRemoteAudio(withRemoteUrl url: URL, mediaInfo: SALockScreenInfo?)` to play audio streamed from a remote location.
Both of these expect a URL of the location of the audio and an optional media information to display on the lockscreen.
@@ -252,7 +252,7 @@ Changes in the duration of the current initialized audio. Especially helpful for
### PlayingStatus
Payload = `SAPlayingStatus`
Changes in the playing status of the player. Can be one of the following 3: `playing`, `paused`, `buffering`.
Changes in the playing status of the player. Can be one of the following 4: `playing`, `paused`, `buffering`, `ended` (audio ended).
### StreamingBuffer
Payload = `SAAudioAvailabilityRange`
+3 -2
View File
@@ -64,7 +64,7 @@ class AudioDiskEngine: AudioEngine {
audioSampleRate = Float(audioFormat?.sampleRate ?? 44100)
audioLengthSeconds = Float(audioLengthSamples) / audioSampleRate
duration = Duration(audioLengthSeconds)
bufferedSeconds = SAAudioAvailabilityRange(startingNeedle: 0, durationLoadedByNetwork: duration, isPlayable: true)
bufferedSeconds = SAAudioAvailabilityRange(startingNeedle: 0, durationLoadedByNetwork: duration, predictedDurationToLoad: duration, isPlayable: true)
} else {
Log.monitor("Could not load downloaded file with url: \(url)")
}
@@ -98,7 +98,7 @@ class AudioDiskEngine: AudioEngine {
if state == .resumed {
state = .suspended
}
delegate?.didEndPlaying()
playingStatus = .ended
}
guard audioSampleRate != 0 else {
@@ -136,6 +136,7 @@ class AudioDiskEngine: AudioEngine {
}
override func invalidate() {
super.invalidate()
//Nothing to invalidate for disk
}
}
+13 -4
View File
@@ -27,6 +27,7 @@ import Foundation
import AVFoundation
protocol AudioEngineProtocol {
var engine: AVAudioEngine { get set }
func play()
func pause()
func seek(toNeedle needle: Needle)
@@ -42,7 +43,7 @@ class AudioEngine: AudioEngineProtocol {
weak var delegate:AudioEngineDelegate?
let key:Key
let engine = AVAudioEngine()
var engine = AVAudioEngine()
let playerNode = AVAudioPlayerNode()
var timer: Timer?
@@ -77,12 +78,16 @@ class AudioEngine: AudioEngineProtocol {
return
}
if status == .ended {
delegate?.didEndPlaying()
}
AudioClockDirector.shared.audioPlayingStatusWasChanged(key, status: status)
}
}
var bufferedSecondsDebouncer: SAAudioAvailabilityRange = SAAudioAvailabilityRange(startingNeedle: 0.0, durationLoadedByNetwork: 0.0, isPlayable: false)
var bufferedSeconds: SAAudioAvailabilityRange = SAAudioAvailabilityRange(startingNeedle: 0.0, durationLoadedByNetwork: 0.0, isPlayable: false) {
var bufferedSecondsDebouncer: SAAudioAvailabilityRange = SAAudioAvailabilityRange(startingNeedle: 0.0, durationLoadedByNetwork: 0.0, predictedDurationToLoad: Double.greatestFiniteMagnitude, isPlayable: false)
var bufferedSeconds: SAAudioAvailabilityRange = SAAudioAvailabilityRange(startingNeedle: 0.0, durationLoadedByNetwork: 0.0, predictedDurationToLoad: Double.greatestFiniteMagnitude, isPlayable: false) {
didSet {
if bufferedSeconds.startingNeedle == 0.0 && bufferedSeconds.durationLoadedByNetwork == 0.0 {
bufferedSecondsDebouncer = bufferedSeconds
@@ -149,7 +154,11 @@ class AudioEngine: AudioEngineProtocol {
func updateIsPlaying() {
if !bufferedSeconds.isPlayable {
playingStatus = .buffering
if bufferedSeconds.bufferingProgress > 0.999 {
playingStatus = .ended
} else {
playingStatus = .buffering
}
return
}
+2 -7
View File
@@ -218,7 +218,7 @@ class AudioStreamEngine: AudioEngine {
let range = converter.pollNetworkAudioAvailabilityRange()
isPlayable = (numberOfBuffersScheduledInTotal >= MIN_BUFFERS_TO_BE_PLAYABLE && range.1 > 0) && predictedStreamDuration > 0
Log.debug("loaded \(range), numberOfBuffersScheduledInTotal: \(numberOfBuffersScheduledInTotal), isPlayable: \(isPlayable)")
bufferedSeconds = SAAudioAvailabilityRange(startingNeedle: range.0, durationLoadedByNetwork: range.1, isPlayable: isPlayable)
bufferedSeconds = SAAudioAvailabilityRange(startingNeedle: range.0, durationLoadedByNetwork: range.1, predictedDurationToLoad: predictedStreamDuration, isPlayable: isPlayable)
}
private func updateNeedle() {
@@ -236,12 +236,6 @@ class AudioStreamEngine: AudioEngine {
var currentTime = TimeInterval(playerTime.sampleTime) / playerTime.sampleRate
currentTime = currentTime > 0 ? currentTime : 0
if currentTime > predictedStreamDuration {
Log.info("reached end of audio")
seek(toNeedle: 0)
pause()
delegate?.didEndPlaying()
}
needle = (currentTime + currentTimeOffset)
}
@@ -297,6 +291,7 @@ class AudioStreamEngine: AudioEngine {
}
override func invalidate() {
super.invalidate()
converter.invalidate()
}
}
+29 -18
View File
@@ -97,7 +97,15 @@ class AudioThrottler: AudioThrottleable {
private var networkData: [NetworkDataWrapper] = []
var shouldThrottle = false
var byteOffsetBecauseOfSeek: UInt = 0
var totalBytesExpected: Int64? //this got sent up twice. Once at beginning of stream and second from network seek. We honor the first send
//This will be sent once at beginning of stream and every network seek
var totalBytesExpected: Int64? {
didSet {
if let bytes = totalBytesExpected {
delegate?.didUpdate(totalBytesExpected: Int64(byteOffsetBecauseOfSeek) + bytes)
}
}
}
var largestPollingOffsetDifference: UInt64 = 1
@@ -110,9 +118,8 @@ class AudioThrottler: AudioThrottleable {
Log.debug("received stream data of size \(pto.getData().count) and progress: \(pto.getProgress())")
self.delegate?.didUpdate(networkStreamProgress: pto.getProgress())
if self.totalBytesExpected == nil, let totalBytesExpected = pto.getTotalBytesExpected() {
if let totalBytesExpected = pto.getTotalBytesExpected() {
self.totalBytesExpected = totalBytesExpected
self.delegate?.didUpdate(totalBytesExpected: totalBytesExpected)
}
let lastItem = self.networkData.last
@@ -152,30 +159,34 @@ class AudioThrottler: AudioThrottleable {
Log.debug("offset: \(offset) within network packet of range: \(wrappedNetworkData.startOffset) to \(wrappedNetworkData.endOffset) is next sent: \(wrappedNetworkData.isNextSent())")
if wrappedNetworkData.alreadySent {
if !wrappedNetworkData.isNextSent() {
var bytesSent: UInt = 0
var current = wrappedNetworkData
// Sometimes the next data packet is smaller than a full audio chunk size, so we need to ensure we send up enough packets for the audio chunk. This prevented Issue #4 where tsreaming would randomly get stuck in a state needing more data up the chain.
// https://github.com/tanhakabir/SwiftAudioPlayer/issues/4
while bytesSent < largestPollingOffsetDifference {
if let next = current.next {
Log.debug("Sending next network packet with range: \(next.startOffset) to \(next.endOffset)")
Log.debug("already sent offset: \(offset) within network packet of range: \(wrappedNetworkData.startOffset) to \(wrappedNetworkData.endOffset)")
var bytesSent: UInt = 0
var current = wrappedNetworkData
// Sometimes the next data packet is smaller than a full audio chunk size, so we need to ensure we send up enough packets for the audio chunk. This prevented Issue #4 where tsreaming would randomly get stuck in a state needing more data up the chain.
// https://github.com/tanhakabir/SwiftAudioPlayer/issues/4
while bytesSent < largestPollingOffsetDifference {
if let next = current.next {
if !next.alreadySent {
Log.info("Sending next network packet with range: \(next.startOffset) to \(next.endOffset), have sent \(bytesSent) bytes so far from \(largestPollingOffsetDifference) bytes")
next.alreadySent = true
delegate?.shouldProcess(networkData: next.data)
bytesSent += next.byteCount
current = next
} else {
return
}
bytesSent += next.byteCount
current = next
} else {
Log.debug("next package doesn't exist, bytes sent so far: \(bytesSent)")
return
}
}
return
}
Log.debug("Found network packet to send with range: \(wrappedNetworkData.startOffset) to \(wrappedNetworkData.endOffset)")
delegate?.shouldProcess(networkData: wrappedNetworkData.data)
Log.info("Found network packet to send with range: \(wrappedNetworkData.startOffset) to \(wrappedNetworkData.endOffset)")
wrappedNetworkData.alreadySent = true
delegate?.shouldProcess(networkData: wrappedNetworkData.data)
return
}
}
@@ -57,28 +57,39 @@ public enum ConverterError: LocalizedError {
public var errorDescription: String? {
switch self {
case .cannotLockQueue:
Log.warn("Failed to lock queue")
return "Failed to lock queue"
case .converterFailed(let status):
Log.warn(localizedDescriptionFromConverterError(status))
return localizedDescriptionFromConverterError(status)
case .failedToCreateDestinationFormat:
Log.warn("Failed to create a destination (processing) format")
return "Failed to create a destination (processing) format"
case .failedToCreatePCMBuffer:
Log.warn("Failed to create PCM buffer for reading data")
return "Failed to create PCM buffer for reading data"
case .notEnoughData:
Log.warn("Not enough data for read-conversion operation")
return "Not enough data for read-conversion operation"
case .parserMissingDataFormat:
Log.warn("Parser is missing a valid data format")
return "Parser is missing a valid data format"
case .reachedEndOfFile:
Log.warn("Reached the end of the file")
return "Reached the end of the file"
case .unableToCreateConverter(let status):
return localizedDescriptionFromConverterError(status)
case .superConcerningShouldNeverHappen:
Log.warn("Weird unexpected reader error. Should not have happened")
return "Weird unexpected reader error. Should not have happened"
case .cannotCreatePCMBufferWithoutConverter:
Log.warn("Could not create a PCM Buffer because reader does not have a converter yet")
return "Could not create a PCM Buffer because reader does not have a converter yet"
case .throttleParsingBuffersForEngine:
Log.warn("Preventing the reader from creating more PCM buffers since the player has more than 60 seconds of audio already to play")
return "Preventing the reader from creating more PCM buffers since the player has more than 60 seconds of audio already to play"
case .failedToCreateParser:
Log.warn("Could not create a parser")
return "Could not create a parser"
}
}
+3 -1
View File
@@ -85,7 +85,9 @@ class AudioParser: AudioParsable {
return max(AVAudioPacketCount(parsedAudioHeaderPacketCount), AVAudioPacketCount(audioPackets.count))
}
guard let sizeOfFileInBytes = expectedFileSizeInBytes, let bytesPerPacket = averageBytesPerPacket else {
let sizeOfFileInBytes: UInt64 = expectedFileSizeInBytes != nil ? expectedFileSizeInBytes! : 0
guard let bytesPerPacket = averageBytesPerPacket else {
return AVAudioPacketCount(0)
}
@@ -29,8 +29,15 @@ import Foundation
public struct SAAudioAvailabilityRange {
let startingNeedle: Needle
let durationLoadedByNetwork: Duration
let predictedDurationToLoad: Duration
let isPlayable: Bool
public var bufferingProgress: Double {
get {
return (startingNeedle + durationLoadedByNetwork) / predictedDurationToLoad
}
}
public var startingBufferTimePositon: Double {
get {
return startingNeedle
@@ -52,4 +59,8 @@ public struct SAAudioAvailabilityRange {
public func contains(_ needle: Double) -> Bool {
return needle >= startingNeedle && (needle - startingNeedle) < durationLoadedByNetwork
}
public func isCompletelyBuffered() -> Bool {
return startingNeedle + durationLoadedByNetwork >= predictedDurationToLoad
}
}
+1
View File
@@ -30,4 +30,5 @@ public enum SAPlayingStatus {
case playing
case paused
case buffering
case ended
}
+4
View File
@@ -35,6 +35,10 @@ protocol LockScreenViewProtocol {
}
extension LockScreenViewProtocol {
func clearLockScreenInfo() {
MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
}
@available(iOS 10.0, *)
func setLockScreenInfo(withMediaInfo info: SALockScreenInfo?, duration: Duration) {
var nowPlayingInfo:[String : Any] = [:]
@@ -243,15 +243,19 @@ extension AudioStreamWorker: URLSessionDataDelegate {
}
guard self.task == dataTask else {
Log.error("stream_error not the same task") //Probably because of seek
Log.error("stream_error not the same task 638283") //Probably because of seek
return
}
guard let totalBytesExpected = totalBytesExpectedForCurrentStream, totalBytesExpected > 0 else {
guard var totalBytesExpected = totalBytesExpectedForCurrentStream else {
Log.monitor("should not be called 223r2")
return
}
if totalBytesExpected <= 0 {
totalBytesExpected = totalBytesReceived
}
totalBytesReceived = totalBytesReceived + Int64(data.count)
let progress = Double(totalBytesReceived)/Double(totalBytesExpected)
@@ -267,7 +271,7 @@ extension AudioStreamWorker: URLSessionDataDelegate {
}
guard self.task == dataTask else {
Log.error("stream_error not the same task")
Log.error("stream_error not the same task 517253")
return
}
@@ -289,8 +293,8 @@ extension AudioStreamWorker: URLSessionDataDelegate {
return
}
guard self.task == task else {
Log.error("stream_error not the same task")
if self.task != task && self.task != nil {
Log.error("stream_error not the same task 3901833")
return
}
+79 -4
View File
@@ -27,6 +27,16 @@ import Foundation
import AVFoundation
public class SAPlayer {
public var DEBUG_MODE: Bool = false {
didSet {
if(DEBUG_MODE) {
logLevel = LogLevel.EXTERNAL_DEBUG
} else {
logLevel = LogLevel.MONITOR
}
}
}
/**
Access to the player.
*/
@@ -35,6 +45,33 @@ public class SAPlayer {
private var presenter: SAPlayerPresenter!
private var player: AudioEngine?
/**
Access the engine of the player. Engine is nil if player has not been initialized with audio.
- Important: Changes to the engine are not safe guarded, thus unknown behaviour can arise from changing the engine. Just be wary and read [documentation of AVAudioEngine](https://developer.apple.com/documentation/avfoundation/avaudioengine) well when modifying,
*/
public var engine: AVAudioEngine? {
get {
return player?.engine
}
}
/**
Corresponding to the overall volume of the player. Volume's default value is 1.0 and the range of valid values is 0.0 to 1.0. Volume is nil if no audio has been initialized yet.
*/
public var volume: Float? {
get {
return player?.engine.mainMixerNode.volume
}
set {
guard let value = newValue else { return }
guard value >= 0.0 && value <= 1.0 else { return }
player?.engine.mainMixerNode.volume = value
}
}
/**
Corresponding to the skipping forward button on the media player on the lockscreen. Default is set to 30 seconds.
*/
@@ -77,6 +114,8 @@ public class SAPlayer {
/**
Total duration of current audio initialized. Returns nil if no audio is initialized in player.
- Note: If you are streaming from a source that does not have an expected size at the beginning of a stream, such as live streams, this value will be constantly updating to best known value at the time.
*/
public var duration: Double? {
get {
@@ -169,21 +208,27 @@ public class SAPlayer {
//MARK: - External Player Controls
extension SAPlayer {
/**
Toggles between the play and pause state of the player if the player is not buffering (thus is playable).
Toggles between the play and pause state of the player. If nothing is playable (aka still in buffering state or no audio is initialized) no action will be taken. Please call `startSavedAudio` or `startRemoteAudio` to set up the player with audio before this.
- Note: If you are streaming, wait till the status from `SAPlayer.Updates.PlayingStatus` is not `.buffering`.
*/
public func togglePlayAndPause() {
presenter.handleTogglePlayingAndPausing()
}
/**
Attempts to play the player even if nothing playable is loaded (aka still in buffering state or no audio is initialized).
Attempts to play the player. If nothing is playable (aka still in buffering state or no audio is initialized) no action will be taken. Please call `startSavedAudio` or `startRemoteAudio` to set up the player with audio before this.
- Note: If you are streaming, wait till the status from `SAPlayer.Updates.PlayingStatus` is not `.buffering`.
*/
public func play() {
presenter.handlePlay()
}
/**
Attempts to pause the player even if nothing playable is loaded (aka still in buffering state or no audio is initialized).
Attempts to pause the player. If nothing is playable (aka still in buffering state or no audio is initialized) no action will be taken. Please call `startSavedAudio` or `startRemoteAudio` to set up the player with audio before this.
- Note:If you are streaming, wait till the status from `SAPlayer.Updates.PlayingStatus` is not `.buffering`.
*/
public func pause() {
presenter.handlePause()
@@ -235,13 +280,19 @@ extension SAPlayer {
- Parameter withSavedUrl: The URL of the audio saved on the device.
- Parameter mediaInfo: The media information of the audio to show on the lockscreen media player (optional).
*/
public func startSavedAudio(withSavedUrl url: URL, mediaInfo: SALockScreenInfo? = nil) {
self.mediaInfo = mediaInfo
presenter.handlePlaySavedAudio(withSavedUrl: url)
}
@available(*, deprecated, renamed: "startSavedAudio")
public func initializeSavedAudio(withSavedUrl url: URL, mediaInfo: SALockScreenInfo? = nil) {
self.mediaInfo = mediaInfo
presenter.handlePlaySavedAudio(withSavedUrl: url)
}
/**
Sets up player to play audio that will be streamed from a remote location.
Sets up player to play audio that will be streamed from a remote location. After this is called, it will connect to the server and start to receive and process data. The player is not playable the SAAudioAvailabilityRange notifies that player is ready for playing (you can subscribe to these updates through `SAPlayer.Updates.StreamingBuffer`). You can alternatively see when the player is available to play by subscribing to `SAPlayer.Updates.PlayingStatus` and waiting for a status that isn't `.buffering`.
- Important: If intending to use [AVAudioUnit](https://developer.apple.com/documentation/avfoundation/audio_track_engineering/audio_engine_building_blocks/audio_enhancements) audio modifiers during playback, the list of audio modifiers under `SAPlayer.shared.audioModifiers` must be finalized before calling this function. After all realtime audio manipulations within the this will be effective.
@@ -250,10 +301,28 @@ extension SAPlayer {
- Parameter withRemoteUrl: The URL of the remote audio.
- Parameter mediaInfo: The media information of the audio to show on the lockscreen media player (optional).
*/
public func startRemoteAudio(withRemoteUrl url: URL, mediaInfo: SALockScreenInfo? = nil) {
self.mediaInfo = mediaInfo
presenter.handlePlayStreamedAudio(withRemoteUrl: url)
}
@available(*, deprecated, renamed: "startRemoteAudio")
public func initializeRemoteAudio(withRemoteUrl url: URL, mediaInfo: SALockScreenInfo? = nil) {
self.mediaInfo = mediaInfo
presenter.handlePlayStreamedAudio(withRemoteUrl: url)
}
public func stopStreamingRemoteAudio() {
presenter.handleStopStreamingAudio()
}
/**
Resets the player to the state before initializing audio and setting media info.
*/
public func clear() {
player = nil
presenter.handleClear()
}
}
@@ -271,6 +340,12 @@ extension SAPlayer: SAPlayerDelegate {
player = AudioStreamEngine(withRemoteUrl: url, delegate: presenter)
}
func clearEngine() {
player?.pause()
player?.invalidate()
player = nil
}
func playEngine() {
becomeDeviceAudioPlayer()
player?.play()
+1
View File
@@ -32,6 +32,7 @@ protocol SAPlayerDelegate: AnyObject, LockScreenViewProtocol {
func startAudioDownloaded(withSavedUrl url: AudioURL)
func startAudioStreamed(withRemoteUrl url: AudioURL)
func clearEngine()
func playEngine()
func pauseEngine()
func seekEngine(toNeedle needle: Needle) //TODO ensure that engine cleans up out of bounds
+24 -3
View File
@@ -60,6 +60,18 @@ class SAPlayerPresenter {
urlKeyMap[url.key] = url
}
func handleClear() {
needle = nil
duration = nil
key = nil
mediaInfo = nil
delegate?.clearLockScreenInfo()
AudioClockDirector.shared.detachFromChangesInDuration(withID: durationRef)
AudioClockDirector.shared.detachFromChangesInNeedle(withID: needleRef)
AudioClockDirector.shared.detachFromChangesInPlayingStatus(withID: playingStatusRef)
}
func handlePlaySavedAudio(withSavedUrl url: URL) {
attachForUpdates(url: url)
delegate?.startAudioDownloaded(withSavedUrl: url)
@@ -71,9 +83,7 @@ class SAPlayerPresenter {
}
private func attachForUpdates(url: URL) {
AudioClockDirector.shared.detachFromChangesInDuration(withID: durationRef)
AudioClockDirector.shared.detachFromChangesInNeedle(withID: needleRef)
AudioClockDirector.shared.detachFromChangesInPlayingStatus(withID: playingStatusRef)
detachFromUpdates()
self.key = url.key
urlKeyMap[url.key] = url
@@ -113,6 +123,17 @@ class SAPlayerPresenter {
})
}
private func detachFromUpdates() {
AudioClockDirector.shared.detachFromChangesInDuration(withID: durationRef)
AudioClockDirector.shared.detachFromChangesInNeedle(withID: needleRef)
AudioClockDirector.shared.detachFromChangesInPlayingStatus(withID: playingStatusRef)
}
func handleStopStreamingAudio() {
delegate?.clearEngine()
detachFromUpdates()
}
@available(iOS 10.0, *)
func handleLockscreenInfo(info: SALockScreenInfo?) {
self.mediaInfo = info
+6
View File
@@ -66,12 +66,16 @@ extension SAPlayer {
/**
Updates to changes in the duration of the current initialized audio. Especially helpful for audio that is being streamed and can change with more data.
- Note: If you are streaming from a source that does not have an expected size at the beginning of a stream, such as live streams, duration will be constantly updating to best known value at the time (which is the seconds buffered currently and not necessarily the actual total duration of audio).
*/
public struct Duration {
/**
Subscribe to updates to changes in duration of the current audio initialized.
- Note: If you are streaming from a source that does not have an expected size at the beginning of a stream, such as live streams, duration will be constantly updating to best known value at the time (which is the seconds buffered currently and not necessarily the actual total duration of audio).
- Note: It's recommended to have a weak reference to a class that uses this function
- Parameter closure: The closure that will receive the updates of the changes in duration.
@@ -136,6 +140,8 @@ extension SAPlayer {
/**
Subscribe to updates to changes in the progress of downloading audio for streaming. Information about range of audio available and if the audio is playable. Look at SAAudioAvailabilityRange for more information. For progress of downloading audio that saves to the phone for playback later, look at AudioDownloading instead.
- Note: For live streams that don't have an expected audio length from the beginning of the stream; the duration is constantly changing and equal to the total seconds buffered from the SAAudioAvailabilityRange.
- Note: It's recommended to have a weak reference to a class that uses this function
- Parameter closure: The closure that will receive the updates of the changes in duration.
+25 -14
View File
@@ -9,22 +9,23 @@
import Foundation
import os.log
// Possible levels of log messages to log
enum LogLevel: Int {
case DEBUG = 1
case INFO = 2
case WARN = 3
case ERROR = 4
case EXTERNAL_DEBUG = 5
case MONITOR = 6
case TEST = 7
}
// Specify which types of log messages to display. Default level is set to WARN, which means Log will print any log messages of type only WARN, ERROR, MONITOR, and TEST. To print DEBUG and INFO logs, set the level to a lower value.
var logLevel: LogLevel = LogLevel.MONITOR
class Log {
private init() {}
// Possible levels of log messages to log
public enum LogLevel: Int {
case DEBUG = 1
case INFO = 2
case WARN = 3
case ERROR = 4
case MONITOR = 5
case TEST = 6
}
// Specify which types of log messages to display. Default level is set to WARN, which means Log will print any log messages of type only WARN, ERROR, MONITOR, and TEST. To print DEBUG and INFO logs, set the level to a lower value.
public static var logLevel: LogLevel = LogLevel.MONITOR
// Used for OSLog
private static let SUBSYSTEM: String = "com.SwiftAudioPlayer"
@@ -68,6 +69,11 @@ class Log {
let log = OSLog(subsystem: SUBSYSTEM, category: "ERROR 🛑🛑🛑🛑")
os_log("%@:%@:%d:: %@", log: log, fileName, functionName, lineNumber, "\(logMessage)")
}
if logLevel.rawValue <= LogLevel.EXTERNAL_DEBUG.rawValue {
let log = OSLog(subsystem: SUBSYSTEM, category: "WARNING")
os_log("%@:%@:%d:: %@", log: log, fileName, functionName, lineNumber, "\(logMessage)")
}
}
/**
@@ -86,7 +92,7 @@ class Log {
public static func monitor(_ logMessage: Any, classPath: String = #file, functionName: String = #function, lineNumber: Int = #line) {
let fileName = URLUtil.getNameFromStringPath(classPath)
if logLevel.rawValue <= LogLevel.ERROR.rawValue {
let log = OSLog(subsystem: SUBSYSTEM, category: "MONITOR 🔥🔥🔥🔥")
let log = OSLog(subsystem: SUBSYSTEM, category: "ERROR 🔥🔥🔥🔥")
os_log("%@:%@:%d:: %@", log: log, fileName, functionName, lineNumber, "\(logMessage)")
}
}
@@ -110,6 +116,11 @@ class Log {
let log = OSLog(subsystem: SUBSYSTEM, category: "WARN ⚠️⚠️⚠️⚠️")
os_log("%@:%@:%d:: %@", log: log, fileName, functionName, lineNumber, "\(logMessage)")
}
if logLevel.rawValue <= LogLevel.EXTERNAL_DEBUG.rawValue {
let log = OSLog(subsystem: SUBSYSTEM, category: "DEBUG")
os_log("%@:%@:%d:: %@", log: log, fileName, functionName, lineNumber, "\(logMessage)")
}
}
/**
+1 -1
View File
@@ -8,7 +8,7 @@
Pod::Spec.new do |s|
s.name = 'SwiftAudioPlayer'
s.version = '2.2.0'
s.version = '2.9.0'
s.summary = 'SwiftAudioPlayer is a Swift based audio player that can handle streaming from a remote location and audio manipulation.'
# This description is used to generate tags and improve search results.