I want to access music files which are available on the iPhone and get it listed (or) get the file into my iPhone application some delegats and start playing it. Is it possible to do it ? Similar to how we access images from device photo album using UIImagePickerController delegate methods.
Thank you!
You can reference MPMediaPickerController class. It functions same as UIImagePickerController class.
-(void)loadDeviceMusic{
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
[everything addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithBool:NO] forProperty:MPMediaItemPropertyIsCloudItem]];
NSArray *itemsFromGenericQuery = [everything items];
for (MPMediaItem *song in itemsFromGenericQuery) {
NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
AVAsset *asset = [AVAsset assetWithURL:assetURL];
NSLog(#"SONGS URL=%#",assetURL);
if ([asset hasProtectedContent] == NO) {
MP3ObjectsClass *objMp3=[[MP3ObjectsClass alloc] init];
objMp3.mp3Url=[song valueForProperty:MPMediaItemPropertyAssetURL];
objMp3.mp3Duration=[song valueForProperty: MPMediaItemPropertyPlaybackDuration];
if([song valueForProperty: MPMediaItemPropertyTitle]){
objMp3.mp3Name=[song valueForProperty: MPMediaItemPropertyTitle];
}else{
objMp3.mp3Name=#"Unknown";
}
if([song valueForProperty: MPMediaItemPropertyArtist]){
objMp3.mp3ArtistName=[song valueForProperty: MPMediaItemPropertyArtist];
}else{
objMp3.mp3ArtistName=#"Unknown";
}
if([song valueForProperty: MPMediaItemPropertyAlbumTitle]){
objMp3.mp3AlbumTitle=[song valueForProperty: MPMediaItemPropertyAlbumTitle];
}else{
objMp3.mp3AlbumTitle=#"Unknown";
}
UIImage *mp3Image=[self getAlbumnArtWorkImage:assetURL];
if(mp3Image){
objMp3.mp3Image=mp3Image;
}else{
objMp3.mp3Image=[UIImage imageNamed:#"DefaultImage"];
}
[mp3Array addObject:objMp3];
}
}
}
-(UIImage *)getAlbumnArtWorkImage :(NSURL *)mp3Url{
AVAsset *asset = [AVURLAsset URLAssetWithURL:mp3Url options:nil];
UIImage *img = nil;
for (NSString *format in [asset availableMetadataFormats]) {
for (AVMetadataItem *item in [asset metadataForFormat:format]) {
if ([[item commonKey] isEqualToString:#"artwork"]) {
img = [UIImage imageWithData:[item.value copyWithZone:nil]];
}
}
}
return img;
}
*** MP3ObjectsClass is a NSObject class. Using above function you can access device music files from iPhone.
First import the AVFoundation/AVFoundation.h framework.
#import <AVFoundation/AVFoundation.h>
-(void)pickAudioFiles
{
MPMediaPickerController *soundPicker=[[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAnyAudio];
soundPicker.delegate=self;
soundPicker.allowsPickingMultipleItems=NO;
[self presentViewController:soundPicker animated:YES completion:nil];
}
-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
MPMediaItem *item = [[mediaItemCollection items] objectAtIndex:0];
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
[mediaPicker dismissViewControllerAnimated:YES completion:nil];
AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];
AVPlayer *player=[[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame=CGRectMake(0, 0, 10, 10);
[self.view.layer addSublayer:playerLayer];
}
and play with [player play];
If you want to use AVAudioPlayer then import AudioToolbox/AudioToolbox.h
Related
I am currently trying to make an app stream raw data from mic over mulipeer connectivity.
I have been using this tutorial as a base https://robots.thoughtbot.com/streaming-audio-to-multiple-listeners-via-ios-multipeer-connectivity
Now however I am struggling with changing the URL from itunes library to my local file.
I am no advanced programmer and this is some kind of summer project.
When the program is getting music from itunes library it uses this code:
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissViewControllerAnimated:YES completion:nil];
if (self.outputStreamer) return;
self.song = mediaItemCollection.items[0];
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info[#"title"] = [self.song valueForProperty:MPMediaItemPropertyTitle] ? [self.song valueForProperty:MPMediaItemPropertyTitle] : #"";
info[#"artist"] = [self.song valueForProperty:MPMediaItemPropertyArtist] ? [self.song valueForProperty:MPMediaItemPropertyArtist] : #"";
MPMediaItemArtwork *artwork = [self.song valueForProperty:MPMediaItemPropertyArtwork];
UIImage *image = [artwork imageWithSize:self.albumImage.frame.size];
if (image)
info[#"artwork"] = image;
if (info[#"artwork"])
self.albumImage.image = info[#"artwork"];
else
self.albumImage.image = nil;
self.songTitle.text = info[#"title"];
self.songArtist.text = info[#"artist"];
[self.session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info copy]]];
NSArray *peers = [self.session connectedPeers];
if (peers.count) {
self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:[self.session outputStreamForPeer:peers[0]]];
[self.outputStreamer streamAudioFromURL:[self.song valueForProperty:MPMediaItemPropertyAssetURL]];
[self.outputStreamer start];
But I want it to get music from the recorder:
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
I have been struggling with this for a while now and would appreciate any kind of help!
Hi I'm working On videos , i would like get the list of video files from library to Display and playing the Videos in my app. can any one help me.
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[allVideos addObject:dic];
}
}];
else
{
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
In swift 4.0 this is how i used fetchAsset() method from Photos framework , to get all videos from photo library.
You can also get the video from specific folder using predicate.
func fetchAllVideos()
{
//let albumName = "blah"
let fetchOptions = PHFetchOptions()
// fetchOptions.predicate = NSPredicate(format: "title = %#", albumName)
//uncomment this if you want video from custom folder
fetchOptions.predicate = NSPredicate(format: "mediaType = %d ", PHAssetMediaType.video.rawValue )
let allVideo = PHAsset.fetchAssets(with: .video, options: fetchOptions)
allVideo.enumerateObjects { (asset, index, bool) in
// videoAssets.append(asset)
let imageManager = PHCachingImageManager()
imageManager.requestAVAsset(forVideo: asset, options: nil, resultHandler: { (asset, audioMix, info) in
if asset != nil {
let avasset = asset as! AVURLAsset
let urlVideo = avasset.url
print(urlVideo)
}
})
}
}
It will open photo library and only display the movie type content.
#import <MobileCoreServices/MobileCoreServices.h>
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentModalViewController:imagePicker animated:YES];
Get List of all Video and Thumbnails
Thanks to #Nikhil , who shared info here, it helped me, but still it required couple of hours to make the code executable as he is missing few things in his answer
So I would like to share my full working code
1.just add frameworks AssetsLibrary, AVFoundation and MediaPlayer.
2.AssetBrowserItem.h and AssetBrowserItem.m here
3.use below code to get list of all videos from ios device lib
4.run app and see Log for videos details
#import "HomeViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "AssetBrowserItem.h"
#interface HomeViewController ()
#property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
#property (nonatomic, strong) NSURL *videoURL;
#property (nonatomic, strong) MPMoviePlayerController *mpVideoPlayer;
#property (nonatomic, strong) NSMutableArray *videoURLArray;
#property (nonatomic, strong) NSMutableArray *assetItems;
#property (nonatomic, strong) NSMutableDictionary *dic;
#end
#implementation HomeViewController
#synthesize assetsLibrary, assetItems,dic;
#synthesize videoURL,videoURLArray, mpVideoPlayer;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Show Video List Methods
- (IBAction)showVideoList:(id)sender
{
[self buildAssetsLibrary];
}
- (void)buildAssetsLibrary
{
assetsLibrary = [[ALAssetsLibrary alloc] init];
ALAssetsLibrary *notificationSender = nil;
videoURLArray = [[NSMutableArray alloc] init];
NSString *minimumSystemVersion = #"4.1";
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
if ([systemVersion compare:minimumSystemVersion options:NSNumericSearch] != NSOrderedAscending)
notificationSender = assetsLibrary;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(assetsLibraryDidChange:) name:ALAssetsLibraryChangedNotification object:notificationSender];
[self updateAssetsLibrary];
}
- (void)assetsLibraryDidChange:(NSNotification*)changeNotification
{
[self updateAssetsLibrary];
}
- (void)updateAssetsLibrary
{
assetItems = [NSMutableArray arrayWithCapacity:0];
ALAssetsLibrary *assetLibrary = assetsLibrary;
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
mpVideoPlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
NSString *title = [NSString stringWithFormat:#"%# %lu", NSLocalizedString(#"Video", nil), [assetItems count]+1];
[self performSelector:#selector(imageFromVideoURL)];
[dic setValue:title forKey:#"VideoTitle"];//kName
[dic setValue:videoURL forKey:#"VideoUrl"];//kURL
AssetBrowserItem *item = [[AssetBrowserItem alloc] initWithURL:videoURL title:title];
[assetItems addObject:item];
[videoURLArray addObject:dic];
NSLog(#"Video has info:%#",videoURLArray);
}
NSLog(#"Values of dictonary==>%#", dic);
//NSLog(#"assetItems:%#",assetItems);
NSLog(#"Videos Are:%#",videoURLArray);
} ];
}
// group == nil signals we are done iterating.
else
{
dispatch_async(dispatch_get_main_queue(), ^{
//[self updateBrowserItemsAndSignalDelegate:assetItems];
// loadImgView.hidden = NO;
// [spinner stopAnimating];
// [loadImgView removeFromSuperview];
//selectVideoBtn .userInteractionEnabled = YES;
});
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
- (UIImage *)imageFromVideoURL
{
UIImage *image = nil;
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
// get the image from
NSError *error = nil;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
// cgimage to uiimage
image = [[UIImage alloc] initWithCGImage:halfWayImage];
[dic setValue:image forKey:#"ImageThumbnail"];//kImage
NSLog(#"Values of dictonary==>%#", dic);
NSLog(#"Videos Are:%#",videoURLArray);
CGImageRelease(halfWayImage);
}
return image;
}
#end
Checkout the blog post to fetch all video assets using Photos Framework
http://iavinashkashyap.blogspot.in/2016/11/get-list-of-all-videos.html
Code:
-(void) getAllVideoAssets{
NSMutableArray *assets = [[NSMutableArray alloc] init];
//Fetch all video assets from Photos
PHFetchResult *assetResults = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:nil];
//get all assets
for (PHAsset *asset in assetResults){
NSLog(#"asset type = %zd", asset.mediaType);
[assets addObject:asset];
}
self.allVideoslistArray = [[NSMutableArray alloc] init];
//create an instance of PHImageManager
PHImageManager *manager = [PHImageManager defaultManager];
for(PHAsset *asset in assets){
//block of code for represent video assets
[manager requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
NSURL *url = (NSURL *)[[(AVURLAsset *)asset URL] fileReferenceURL];
UIImage *thumbnail = [self createThunbnailImage:url];
[self.allVideoslistArray addObject:#{#"VideoUrl":url,#"ThumbnailImage":thumbnail, #"VideoAsset":asset}];
}
}];
}//end for loop
}
use this method To pick videos From Library.
//Call this method.
[self startMediaBrowserFromViewController: self usingDelegate: self];
- (BOOL) startMediaBrowserFromViewController: (UIViewController*) controller usingDelegate: (id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>) delegate{
if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO) || (delegate == nil) || (controller == nil))
return NO;
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
mediaUI.mediaTypes = [[[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil] autorelease];
mediaUI.allowsEditing = YES;
mediaUI.delegate = self;
mediaUI.videoMaximumDuration = 60.0;
//mediaUI.videoQuality = UIImagePickerControllerQualityTypeLow;
[controller presentModalViewController: mediaUI animated: YES];
return YES;
}
Please refer below link.
It may be helpful to you
http://www.raywenderlich.com/13418/how-to-play-record-edit-videos-in-ios
Good luck !!!
I have training app i want that when user click recordVideo button camera should launch to record video, is there any way to do this in ipad app.I have done audio recording already i need to do video recording.
//for video..
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/Mediaplayer.h>
#import <CoreMedia/CoreMedia.h>
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSArray *mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
picker.mediaTypes = mediaTypes ;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo ;
[self presentModalViewController:picker animated:NO];
[picker release];
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#" Camera Facility is not available with this Device" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
for saving into Document folder & it also save in photo Library
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
//for video
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"video url-%#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSString * videoName = [NSString stringWithFormat:#"student_%d_%d.mp4",stud_id,imgVidID];
videoPath = [documentsDirectory stringByAppendingPathComponent:videoName];
NSLog(#"video path-%#",videoPath);
[videoData writeToFile:videoPath atomically:YES];
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath,nil,nil,nil);
}
Try this ::
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[self dismissViewControllerAnimated:NO completion:nil];
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
// Code To give Name to video and store to DocumentDirectory //
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy||HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
theDate = [dateFormat stringFromDate:now];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mov",documentsDirectory,theDate]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
}
}
Hopefully, It'll help you.
Thanks.
Just try it :
-(void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
NSString *moviePath = [[info objectForKey: UIImagePickerControllerMediaURL] path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)){
UISaveVideoAtPathToSavedPhotosAlbum (moviePath,self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
}
-(void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
if (error) {
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeRed title:#"Video Saving Failed" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:1.0];
}
else{
NSURL *videoURl = [NSURL fileURLWithPath:videoPath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURl options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
self.strUploadVideoURL = videoPath;
[imgPhoto setImage:[[[UIImage alloc] initWithCGImage:imgRef] autorelease]];
intWhenPushView = 2;
btnShare.enabled = YES;
btnFacebookShare.enabled = YES;
CGImageRelease(imgRef);
[generate release];
[asset release];
}
}
I am trying to play a song from my iPhone music library using AVPlayer. Everything seems ready to play, but the player simply won't make any sound. I've been struggling with this for a while, any help would be greatly appreciated!
Note: I realize I could use AVAudioPlayer, but I would like to read the file right from my music library and, to my understanding, AVAudioPlayer doesn't support that (I would have to export the song first, taking up more time). I cannot use MPMusicPlayerController because the end goal is to turn the song into NSData and play it on another device.
Above all, I would like to know WHY this code isn't playing:
NSArray *itemsFromQuery = [[MPMediaQuery songsQuery] items];
MPMediaItem *song = [itemsFromQuery objectAtIndex:29];
NSURL *songURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:songURL options:nil];
NSArray *keyArray = [[NSArray alloc] initWithObjects:#"tracks", nil];
[urlAsset loadValuesAsynchronouslyForKeys:keyArray completionHandler:^{
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:urlAsset];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
while (true) {
if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay) {
break;
}
}
if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay) {
NSLog(#"Ready to play");
[player play];
}
else
NSLog(#"Not ready to play");
}];
The output is "Ready to play", and the "rate" property of the AVPlayer is 1.0 after I call the play method. The MPMediaItem exists, and I can use the valueForProperty method to obtain the correct title, artist, etc. Any ideas why no sound is coming from the player?
Found something that worked:
I made the AVPlayer a property (thanks for the tip meggar!)
I made sure the AVPlayer was nil before using the initWithAsset method.
NSArray *itemsFromQuery = [[MPMediaQuery songsQuery] items];
MPMediaItem *song = [itemsFromQuery objectAtIndex:0];
NSURL *songURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:songURL options:nil];
NSArray *keyArray = [[NSArray alloc] initWithObjects:#"tracks", nil];
[urlAsset loadValuesAsynchronouslyForKeys:keyArray completionHandler:^{
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:urlAsset];
player = nil;
player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
while (true) {
if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay)
break;
}
[player play];
}];
Hope this helps someone out!
Another reason is configuring AVAudioSession. Worked for me.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
- (IBAction)playingSong {
MPMediaItem *theSong = [[MPMusicPlayerController iPodMusicPlayer] nowPlayingItem];
NSString *theTitle = [song valueForProperty:MPMediaItemPropertyTitle];
NSString *theArtist = [song valueForProperty:MPMediaItemPropertyArtist];
NSString *nowPlaying = [NSString stringWithFormat:#"#NowPlaying %# by %#", theTitle, theArtist];
tweetTextView.text = [NSString stringWithFormat:#"%#%#", nowPlaying, tweetTextView.text];
[self setChars];
}
- (IBAction)sendMusicTweet:(id)sender {
TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
[tweetViewController setInitialText:tweetTextView.text];
[self presentModalViewController:tweetViewController animated:YES];
}
I have imported the frameworks. But I don't know how to resolve this errors... What can I do? Thanks :)
It's declared as 'theSong', not song. You never declared a pointer to tweetTextView in the .h and setChars isn't defined in ANY file.
Your code SHOULD BE:
- (IBAction)playingSong {
MPMediaItem *theSong = [[MPMusicPlayerController iPodMusicPlayer] nowPlayingItem];
NSString *theTitle = [theSong valueForProperty:MPMediaItemPropertyTitle];
NSString *theArtist = [theSong valueForProperty:MPMediaItemPropertyArtist];
NSString *nowPlaying = [NSString stringWithFormat:#"#NowPlaying %# by %#", theTitle, theArtist];
//Declare tweetTextView in the .h!!
tweetTextView.text = [NSString stringWithFormat:#"%#%#", nowPlaying, tweetTextView.text];
//[self setChars]; Define this In the .h!
}
- (IBAction)sendMusicTweet:(id)sender {
TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
[tweetViewController setInitialText:tweetTextView.text];
[self presentModalViewController:tweetViewController animated:YES];
}