Play Song using MPMediaItemPropertyTitle - ios

I get Song title in TableView using this code:
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
for (MPMediaItem *song in itemsFromGenericQuery) {
NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
[songTitleArray addObject:songTitle];
}
Now I want to play that song inside tableView I added Two button play and Stop how to play using Title in same ViewController.

To play song you can do something like :
MPMusicPlayerController *controller = [MPMusicPlayerController iPodMusicPlayer];
MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:arrayOfMediaItems];
MPMediaItem *item = [collection representativeItem];
[controller setQueueWithItemCollection:collection];
[controller setNowPlayingItem:item];
[controller prepareToPlay];
[controller play];
You can also use AVPlayer to play song, after picking it through MPMediaPickerController :
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker
didPickMediaItems: (MPMediaItemCollection *) collection {
MPMediaItem *item = [[collection items] objectAtIndex:0];
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
[self dismissModalViewControllerAnimated: YES];
// Play the item using MPMusicPlayer
MPMusicPlayerController* appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];
[appMusicPlayer setQueueWithItemCollection:collection];
[appMusicPlayer play];
// Play the item using AVPlayer
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];
}

Related

Play Video in iOS

I am trying to play a video which is stored on my device trying both AVPlayer and MPMoviePlayerController.
Video URl is: file:///var/mobile/Containers/Data/Application/73695F3E-9351-447B-BB8A-0B4A62CE430F/Documents/08-03-201711:48:50.3gp. Now the problem is I get blank screen.
AVPlayer *player = [AVPlayer playerWithURL:fileURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
[player pause];
[player play];
playerViewController.player = player;
[self addChildViewController: playerViewController];
[self.view addSubview: playerViewController.view];
//[playerViewController.player play];//Used to Play On start
[self presentViewController:playerViewController animated:YES completion:nil];
I think the problem is in link. What I am doing is getting local directory link and append name with that link.
I will you good solution.It works perfectly.
ViewController.h
#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) AVPlayerViewController *playerViewController;
- (IBAction)actionPlayVideo:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController (){
NSURL *vedioURL;
}
#end
#implementation ViewController
#synthesize playerViewController;
- (IBAction)actionPlayVideo:(id)sender{
NSString *fullpath = [[self documentsDirectory] stringByAppendingPathComponent:#"yourdate.3gp"];
vedioURL =[NSURL fileURLWithPath:fullpath];
AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:vedioURL];
AVPlayer* playVideo = [[AVPlayer alloc] initWithPlayerItem:playerItem];
playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = playVideo;
playerViewController.player.volume = 0;
playerViewController.view.frame = self.view.bounds;
[self.view addSubview:playerViewController.view];
[playVideo play];
}
-(NSString *)documentsDirectory{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
EDIT: MPMoviePlayerController is Deprecated Now. So I have used AVPlayerViewController. and written the following code:
NSURL *videoURL = [NSURL fileURLWithPath:filePath];
//filePath may be from the Bundle or from the Saved file Directory, it is just the path for the video
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
//[playerViewController.player play];//Used to Play On start
[self presentViewController:playerViewController animated:YES completion:nil];
Please do not forget to import following frameworks:
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
You can use MPMoviePlayerController to play local file.
Add Mediaplayer framework and do #import in your viewController.
Drag and drop your video file you created on desktop into the xcode.
Get the path of the local video.
NSStringthePath=[[NSBundle mainBundle] pathForResource:#"yourVideo" ofType:#"MOV"];
NSURLtheurl=[NSURL fileURLWithPath:thePath];
Initialize the moviePlayer with your path.
self.moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[self.moviePlayer.view setFrame:CGRectMake(40, 197, 240, 160)];
[self.moviePlayer prepareToPlay];
[self.moviePlayer setShouldAutoplay:NO]; // And other options you can look through the documentation.
[self.view addSubview:self.moviePlayer.view];
To control what is to be done after playback:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playBackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
//playBackFinished will be your own method.
EDIT 2: To handle completion for AVPlayerViewController rather than MPMoviePlayerController, use the following...
AVPlayerItem *playerItem = player.currentItem;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playBackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
In this example, I dismiss the AVPlayerViewController after completion:
-(void)playBackFinished:(NSNotification *) notification {
// Will be called when AVPlayer finishes playing playerItem
[playerViewController dismissViewControllerAnimated:false completion:nil];
}
It may happen because of your file url is incorrect.
Try below codes to get the path of your answer.
If you have the video in your mac, then copy it in to your project firstly, just drug it to Xcode.
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"08-03-201711:21:67" ofType:#"3gp"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
And use this path to AVPlayer
AVPlayer *player = [AVPlayer playerWithURL:fileURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
[player pause];
[player play];
playerViewController.player = player;
[self addChildViewController: playerViewController];
[self.view addSubview: playerViewController.view];
**As I review your code, a blank screen may caused by you adding AVPlayer it into layer but not as subview/childviewcontroller. So try my code!

How to play protected video content in iOS using AVPlayer

I have used the below implementation to play a protected video content from the media server, but it shows play icon with cross line.
After login app need to sync the cookies to the media assets to play the protected video after authentication.By using AVURLAsset, we are streaming the protected video but its not working.
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSDictionary *opt = #{
AVURLAssetReferenceRestrictionsKey: #(AVAssetReferenceRestrictionForbidRemoteReferenceToLocal),
AVURLAssetHTTPCookiesKey: cookies
};
AVAsset *asset = [AVURLAsset URLAssetWithURL:linkUrl//Media protected URL(http://www.example.com/media/video/media_mp4)
options:opt];
AVPlayerItem * item = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:item];
AVPlayerViewController *playerVC = [[AVPlayerViewController alloc]init];
playerVC.player = player;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self presentViewController:playerVC animated:NO completion:nil];
});
After searching a lot and finally it worked for me. I got the app cookies from NSHTTPCookieStorage class. Then using this I created a dictionary with key value pairs as below,
#{AVURLAssetHTTPCookiesKey : cookies}
Then I set this dictionary to the options in the AVURLAsset URLAssetWithURL:linkUrl options:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:linkUrl options:#{AVURLAssetHTTPCookiesKey : cookies}];
AVPlayerItem * item = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:item];
AVPlayerViewController *playerVC = [[AVPlayerViewController alloc]init];
playerVC.player = player;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self presentViewController:playerVC animated:NO completion:nil];
});

AVPlayer - how to reset play button

Im working on a app which stream a audio file online. The code below is working, but when the audio file ends, the play button don't reset. The button is still pressed, and before the user can play the audio file again, the user have to press the button 2 times.
My question is: How do i reset the play button automatically after the audio file ends?
Here is my code:
-(IBAction)togglePlayPauseTapped:(id)sender
{
if(self.togglePlayPause.selected) {
[self.audioPlayer pause];
[self.togglePlayPause setSelected:NO];
} else {
[self.audioPlayer play];
[self.togglePlayPause setSelected:YES];
self.audioPlayer = [[AVPlayer alloc] init];
NSString *urlString = #"MYURL";
NSURL* urlStream = [NSURL URLWithString:urlString];
AVPlayerItem * currentItem = [AVPlayerItem playerItemWithURL:urlStream];
[self.audioPlayer replaceCurrentItemWithPlayerItem:currentItem];
[self.audioPlayer play];
}
}`
Set the delegate of audioPlayer to self and make sure the designated ViewController can receive AVAudioPlayer Delegate calls. Then implement the audioPlayerDidFinishPlaying method and call your togglePlayPauseTapped method:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self togglePlayPauseTapped:nil];
}
The total should look something like this:
Edit:
And change this
self.audioPlayer = [[AVPlayer alloc] init];
To this:
self.audioPlayer = [[AVAudioPlayer alloc] init];

Stream Audio with AVPlayer

I'm trying to play audio from a URL using AVPlayer when a row is selected in a table view but it doesn't play. What am I doing wrong?
Here is the code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *streamingString = [NSString stringWithFormat:#"%#.json?client_id=fc886d005e29ba78f046e5474e3fdefb", [streamURLArray objectAtIndex:indexPath.row]];
NSURL *streamingURL = [NSURL URLWithString:streamingString];
NSLog(#"%#", streamingURL);
AVPlayer *player = [AVPlayer playerWithURL:streamingURL];
[player play];
player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
}
An example of streamingURL when I log it is this.
http://api.soundcloud.com/tracks/146814101/stream.json?client_id=fc886d005e29ba78f046e5474e3fdefb
declare AVAudioPlayer globally in your .h file
like this AVPlayer *player;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *streamingString = [NSString stringWithFormat:#"%#.json?client_id=fc886d005e29ba78f046e5474e3fdefb", [streamURLArray objectAtIndex:indexPath.row]];
NSURL *streamingURL = [NSURL URLWithString:streamingString];
NSLog(#"%#", streamingURL);
player = [AVPlayer playerWithURL:streamingURL];
[player play];
player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
}
You'll find numerous audio streaming kit all around GitHub.
https://github.com/tumtumtum/StreamingKit
https://github.com/muhku/FreeStreamer
https://github.com/mattgallagher/AudioStreamer
call this method
[player prepareToPlay];
before calling
[player play];
It may help to u.

Creating an AVPlayer for video

I am creating an AVPlayer to display a video. I have some code to create the Player but nothing displays. I'm not sure if the URL is not working or if the player it's self is not working.
Here is the code I am using to create the player:
self.playing = NO;
AVPlayer *player = [[AVPlayer alloc] init];
player = [player initWithURL:self.videoURL];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
[[[self view] layer] insertSublayer:playerLayer atIndex:3];
[playerLayer setFrame:self.view.bounds];
[player play];
Here is the code to save the video:
self.videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"%#", self.videoURL);
DetailViewController *detailViewController = [[DetailViewController alloc] init];
detailViewController.videoURL = self.videoURL;

Resources