The articles
Find similar images in IOS albums radar diffusion effect search device implementation of a simple sandbox file browser implementation of a simple breadcrumb navigation
What are media resources
In IOS, media resources are roughly divided into two types: audio and video (note that videos in albums are not media), such as music and movies in iPhone, and media resources in AppleMusic and AppleTv.
Classification of media resources
Let’s start with the official definition of media types
typedef NS_OPTIONS(NSUInteger.MPMediaType) {
// audio
MPMediaTypeMusic = 1 << 0.MPMediaTypePodcast = 1 << 1.MPMediaTypeAudioBook = 1 << 2.MPMediaTypeAudioITunesU MP_API(ios(5.0), tvos(9.0), watchos(5.0), macos(10.122.=))1 << 3.MPMediaTypeAnyAudio = 0x00ff.// video
MPMediaTypeMovie MP_API(ios(5.0), tvos(9.0), watchos(5.0), macos(10.122.=))1 << 8.MPMediaTypeTVShow MP_API(ios(5.0), tvos(9.0), watchos(5.0), macos(10.122.=))1 << 9.MPMediaTypeVideoPodcast MP_API(ios(5.0), tvos(9.0), watchos(5.0), macos(10.122.=))1 << 10.MPMediaTypeMusicVideo MP_API(ios(5.0), tvos(9.0), watchos(5.0), macos(10.122.=))1 << 11.MPMediaTypeVideoITunesU MP_API(ios(5.0), tvos(9.0), watchos(5.0), macos(10.122.=))1 << 12.MPMediaTypeHomeVideo MP_API(ios(7.0), tvos(9.0), watchos(5.0), macos(10.122.=))1 << 13.MPMediaTypeAnyVideo MP_API(ios(5.0), tvos(9.0), watchos(5.0), macos(10.122.=))0xff00.MPMediaTypeAny = ~0UL
} MP_API(ios(3.0), tvos(9.0), watchos(5.0), macos(10.122.));
Copy the code
By the official definition given to us, and then we can sort it out a little bit. There are two types of system media resources in IOS. One is audio, which includes music, audiobooks, blogs and itunsU; the other is video, which includes movies, TV, video blogs, MV,itunesU and home videos.
Media Resource acquisition
Because there are too many types of media resources, but they are all acquired in the same way, we complete the acquisition of media resources by selecting the media of music type.
Get all music
Start by constructing a Query that queries all the music
MPMediaQuery* query = [[MPMediaQuery alloc] init];
MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInteger:MPMediaTypeMusic] forProperty:MPMediaItemPropertyMediaType];
[query addFilterPredicate:predicate];
Copy the code
We create a filter called predicate for the Query to Query all the music. The filter adds a filter to the Query. This added filter is filtered by the type of media, if it is MPMediaTypeMusic.
As shown in the above, the filter by traversing the form and get the MPMediaItemPropertyMediaType attributes, and then use this attribute and MPMediaTypeMusic to conform to the requirements of the screening. According to the above comparison, Item1,Item3 and Item4 meet the requirements and pass the screening.
In the same way we can get different types of media by setting other filter media types to the filter. For example, set the filter value to MPMediaTypeMovie to get movie-type media.
NSArray* itemLists = [query items];
Copy the code
We then return the filter results by calling the Items method of the Query
Shortcut to construct Query
Of course, the system also provides us with several queries for specific media, so that we can quickly construct the query.
/// Create a media query that matches the music item and group and sort the collection by album name
+ (MPMediaQuery *)albumsQuery;
/// Create a media query that matches the music item and group and sort the collection by artist name
+ (MPMediaQuery *)artistsQuery;
/// Create a media query that matches the music item and group and sort the collection by song name
+ (MPMediaQuery *)songsQuery;
/// Create media queries that match the entire library and group and sort the collection by playlist name
+ (MPMediaQuery *)playlistsQuery;
/// Create media queries that match podcast items and group and sort collections by podcast name
+ (MPMediaQuery *)podcastsQuery;
/// Create media queries that match audio book items and group and sort collections by audio book names
+ (MPMediaQuery *)audiobooksQuery;
/// Create a media query to match edit items and group and sort collections by album name
+ (MPMediaQuery *)compilationsQuery;
/// Create a media query that matches all media entries and group and sort the collection by composer name
+ (MPMediaQuery *)composersQuery;
/// Create a media query that matches all media items and group and sort the collection by genre name
+ (MPMediaQuery *)genresQuery;
Copy the code
Media resource properties
Because there are too many media resource attributes, I directly use the following table to represent
attribute | role |
---|---|
MPMediaItemPropertyPersistentID | Key for the persistent identifier of a media item. |
MPMediaType | Properties used to define media item types. |
MPMediaItemPropertyTitle | The title (or name) of the media project. |
MPMediaItemPropertyAlbumTitle | Name of Media album |
MPMediaItemPropertyAlbumPersistentID | Persistent ID of media album |
MPMediaItemPropertyArtist | Media Author Information |
MPMediaItemPropertyArtistPersistentID | Persistent ID of media author information |
MPMediaItemPropertyAlbumArtist | Album Author Information |
MPMediaItemPropertyAlbumArtistPersistentID | Album author information Persistent ID |
MPMediaItemPropertyGenre | Media genres |
MPMediaItemPropertyGenrePersistentID | The persistent identifier of the genre |
MPMediaItemPropertyComposer | Composer information |
MPMediaItemPropertyComposerPersistentID | The composer persists the ID |
MPMediaItemPropertyPlaybackDuration | PlaybackDuration |
MPMediaItemPropertyAlbumTrackNumber | Album Track Number |
MPMediaItemPropertyAlbumTrackCount | Album Tracks |
MPMediaItemPropertyDiscNumber | Record number |
MPMediaItemPropertyDiscCount | Number of albums |
MPMediaItemPropertyArtwork | Works of art |
MPMediaItemPropertyIsExplicit | A Boolean value indicating whether a media item contains explicit content |
MPMediaItemPropertyLyrics | The lyrics |
MPMediaItemPropertyIsCompilation | A Boolean value that determines whether the media can be edited |
MPMediaItemPropertyReleaseDate | The release date |
MPMediaItemPropertyBeatsPerMinute | The number of music beats per minute for a media project corresponds to the BPM field in the Information TAB of the Get Info dialog box in iTunes. |
MPMediaItemPropertyComments | Text information about media items corresponds to the Comments field in the Information TAB of the Get Information dialog box in iTunes. |
MPMediaItemPropertyAssetURL | A URL pointing to a media project from which you can create an AVAsset object (or other URL-based AVFoundation object), using whatever options you need. |
MPMediaItemPropertyIsCloudItem | Check if it is an iCloud Item |
MPMediaItemPropertyHasProtectedAsset | A Boolean value indicating that the media item is wrapped in the DRM and cannot be used through the standard playback API. |
MPMediaItemPropertyPodcastTitle | The title of the podcast. |
MPMediaItemPropertyPodcastPersistentID | A persistent identifier for a podcast. |
MPMediaItemPropertyPlayCount | The number of times the user played the media item. |
MPMediaItemPropertySkipCount | Number of times the user skipped playing the item. |
MPMediaItemPropertyRating | The user-specified rating of the object in the range [0…5], where a value of 5 represents the most favorable rating. |
MPMediaItemPropertyLastPlayedDate | The most recent calendar date for a user to play a media item. |
MPMediaItemPropertyUserGrouping | Corresponds to the Grouping field in the Information TAB of the Get Information dialog box in iTunes. |
MPMediaItemPropertyBookmarkTime | The user’s position in the media project when it was last played. |
MPMediaItemPropertyDateAdded | The date the media item was added to the user’s media library. |
MPMediaItemPropertyPlaybackStoreID | An identifier used to queue a track. |
Gets the size of the resource
We can not find the specific size of the resource after searching the properties of the media resource. How can we obtain the size of the media resource?
The answer is through AVAssetExportSession and KVO
AVAssetExportSession Obtains the size of the media resource
self.assetURL = MPMediaItem.assetURL AVAsset *asset = [AVAsset assetWithURL:self.assetURL];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: asset presetName:AVAssetExportPresetAppleM4A];
exporter.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
self.fileSize = exporter.estimatedOutputFileLength;
Copy the code
Build an AVAsset object based on the assetURL property of MPMediaItem and create an AVAssetExportSession from that AVAsset object, Set up AVAssetExportSession default AVAssetExportPresetAppleM4A derived
Note that there can’t be AVAssetExportPresetPassthrough export in the assets of the original format.
Then set the export duration to the playing duration of the resource being exported
exporter.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
Copy the code
If there is no set length is derived, forecast export size size estimates byte 0 “estimatedOutputFileLength export file
The estimated file size is different from the actual size because AVAssetExportSession transcodes the estimated file size after transcoding.
Use KVO to get the file size attribute of MPMediaitem
self.fileSize = [[self.item valueForProperty:@"fileSize"] integerValue];
Copy the code
The size of the resource obtained using KVO is equal to the size of the resource stored in the phone in its original format.
Exporting Media Resources
Also taking music as an example, we will complete the export of resources
AssetUrl
According to the media resources, the properties of the MPMediaItemPropertyAssetURL, we can obtain the media resources in storage address.
Copyright issues
If you use account A to import songs or movies from PC to account B’s iPhone, if the songs or movies in account A are copyrighted, those songs or movies with versions cannot be played.
In MPMediaItem, there is the version of the song or movie, there is the composer, name, cover and other media metadata, but there is no asstURL resource path.
The copyright files of the video type are.m4v. The copyright files of the audio type are.m4p
Export resources using AVAssetExportSession
Note that we cannot export versioned media resources to our sandbox directory due to copyright issues.
After we have AssetUrl for the media resource, we initialize an AVAsset to load the resource and set up the sandbox path to export to.
View the file formats that can be exported
See the supportedFileTypes of AVAssetExportSession to find the file formats supported for export, Here we set the export file format for AVFileTypeCoreAudioFormat and corresponding types of UTI is com. Apple. Coreaudio – format
(
"com.apple.quicktime-movie"."com.apple.m4a-audio"."public.mpeg-4"."com.apple.m4v-video"."public.3gpp"."org.3gpp.adaptive-multi-rate-audio"."com.microsoft.waveform-audio"."public.aiff-audio"."public.aifc-audio"."com.apple.coreaudio-format"
)
Copy the code
Setting preset values
PresetName Sets the default value for the exported template. Here we set a value of the template AssetExportSession AVAssetExportPresetPassthrough this default values can not be able to resources for recoding of written into the sandbox.
Complete export resource code
NSURL* outputUrl = [NSURL fileURLWithPath:path];
AVAsset* asset = [AVAsset assetWithURL:item.assetURL];
AVAssetExportSession *session =[[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
session.outputURL = [NSURL fileURLWithPath:path];
session.outputFileType = AVFileTypeCoreAudioFormat;
session.metadata = asset.metadata;
[session exportAsynchronouslyWithCompletionHandler:^{
// Determine the export status
switch (session.status) {
case AVAssetExportSessionStatusCompleted: {// Export is complete
NSLog(Export successful %@,outputUrl.absoluteString);
complete(outputUrl,YES);
}
break;
case AVAssetExportSessionStatusFailed: {// Failed to export
NSLog(@" Export error %@",session.error);
complete(nil.NO);
}
break;
default:
complete(nil.NO);
break; }}];Copy the code