Exploring MusicKit and Apple Music API
Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!
In the latest update to MusicKit announced at WWDC 2024, the team introduced a new feature: crossfade. While this appears to be the only major change for us MusicKit developers this year, it is a welcome addition for audio playback. Also, I assume that there are numerous performance improvements and optimizations happening under the hood. Let’s dive into the details of this new feature and how to implement it in our iOS app.
The New Crossfade Feature
The crossfade feature allows for a smooth transition between tracks, creating a better listening experience. This functionality is implemented through a new Transition
enum and associated properties in the ApplicationMusicPlayer
class.
The ApplicationMusicPlayer Class
The ApplicationMusicPlayer
class has been updated to include a new transition
property:
@available(iOS 15.0, tvOS 15.0, visionOS 1.0, macOS 14.0, *)
@available(watchOS, unavailable)
public class ApplicationMusicPlayer : MusicPlayer {
public static let shared: ApplicationMusicPlayer
public var queue: ApplicationMusicPlayer.Queue
@available(iOS 18.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public var transition: MusicPlayer.Transition
}
The transition
property allows you to set the transition style between playing items. By default, it is set to .none
, meaning there is no transition between tracks.
The Transition Enum
The new Transition
enum is where the magic happens:
@available(iOS 18.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
extension MusicPlayer {
public enum Transition : Equatable, Hashable, Sendable {
case none
case crossfade(options: MusicPlayer.Transition.CrossfadeOptions)
public static let crossfade: MusicPlayer.Transition
public static func crossfade(duration: TimeInterval?) -> MusicPlayer.Transition
}
}
This enum introduces the crossfade
case, which can be used with or without specifying a duration.
Implementing Crossfade in Your App
Using the new crossfade feature in your app is straightforward. Here is a simple example of how to enable crossfade with a 2-second duration:
if #available(iOS 18.0, *) {
ApplicationMusicPlayer.shared.transition = .crossfade(duration: 2)
}
This sets a 2-second crossfade transition between the music items. Remember to wrap this in an availability check, as the feature is only available from iOS 18.0 onwards!
Exploring MusicKit and Apple Music API
Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!