I am working on a iphone5 app and i need some advice on the vibration motor.
i goggled the things but cant find how can i manually rotate my iPhone from the code.please guide me... or give any link or ideas..
What i want to do is vibrate the phone while recordign the video .
but my problem is when i start the vibration it cant recrod the video.. i found that it will not work when audio is capturing running.. so i tried with mute the sound while recording but its not working still
following is my code..
//
// APPViewController.m
//
//
// Created by Rafael Garcia Leiva on 29/04/13.
// Copyright (c) 2013 Appcoda. All rights reserved.
//
#import "APPViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#interface APPViewController ()
#end
#implementation APPViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated {
self.movieController = [[MPMoviePlayerController alloc] init];
[self.movieController setContentURL:self.movieURL];
[self.movieController.view setFrame:CGRectMake ( 0, 0, 320, 476)];
[self.view addSubview:self.movieController.view];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.movieController];
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0];
[self.movieController play];
[self setupAudio];
}
- (IBAction)takeVideo:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:NULL];
while(TRUE){
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}
- (void)setupAudio {
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
self.movieURL = info[UIImagePickerControllerMediaURL];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)moviePlayBackDidFinish:(NSNotification *)notification {
[[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self.movieController stop];
[self.movieController.view removeFromSuperview];
self.movieController = nil;
}
#end
i am vibrating my phone with this but its working vibrating or video recording...if video will record with no sound then even its ok for me..
while(TRUE){
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
thanks
I'm guessing the recording APIs might internally disable vibration (and other system sounds too) because vibration during recording would seriously degrade the video and audio quality of the recording.
Of course I'm only guessing. That seems like the sort of thing Apple might do, and I think in most cases that's what you would want (e.g., you wouldn't want a recording to be ruined by an incoming text message or phone call). I'm curious why you want to vibrate the device during recording - is it for a special effect?
Related
i being trying to play video from lib but i cant figure out what im doing wrong i have tried many things and its not showing any kind of error my code is below
- (void) imagePickerController: (UIImagePickerController *) picker
didFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
NSURL *url = [[NSURL alloc]initWithString:mediaType];
NSLog(#"%#",url);
[self dismissModalViewControllerAnimated:NO];
/* Create a new movie player object. */
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
if (player)
{
/* Specify the URL that points to the movie file. */
[player setContentURL:url];
/* Add a background view as a subview to hide our other view controls
underneath during movie playback. */
CGRect viewInsetRect = CGRectInset ([self.view bounds],
kMovieViewOffsetX,
kMovieViewOffsetY );
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:viewInsetRect];
[player view].backgroundColor = [UIColor lightGrayColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[self.view addSubview: [player view]];
[player setCurrentPlaybackRate:0.5];
[player play];
}
// Register for the playback finished notification
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: #selector(myMovieFinishedCallback:)
name: MPMoviePlayerPlaybackDidFinishNotification
object: player];
}
// When the movie is done, release the controller.
-(void) myMovieFinishedCallback: (NSNotification*) aNotification
{
MPMoviePlayerController *playerr = [aNotification object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification
object:playerr];
[playerr stop];
[self.view removeFromSuperview];
[playerr autorelease];
}
what happen is first presetModelViewController is getting displayed then i can shows videos which are in my lib i can select one of them but when i choose video then it shows my grey color view and nothing else and my video is not getting played.
If you could find any errors in my code and can help me with this then it will be great help.
Please go through the below link will help you with your existing issue and also implementation.
http://www.raywenderlich.com/13418/how-to-play-record-edit-videos-in-ios
NSURL *videoURL = [NSURL URLWithString:videoURLString];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:videoURL];
[moviePlayer prepareToPlay];
[moviePlayer play];
[self.view addSubview:moviePlayer.view];
This is what solved my problem thanks to spider1983
- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
[self dismissModalViewControllerAnimated: YES];
}
// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
didFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
// Handle a movie capture
if (CFStringCompare ((__bridge_retained CFStringRef)mediaType, kUTTypeMovie, 0)
== kCFCompareEqualTo) {
NSString *moviePath = [[info objectForKey:
UIImagePickerControllerMediaURL] path];
NSLog(#"%#",[info objectForKey:
UIImagePickerControllerMediaURL]);
/* Create a new movie player object. */
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[info objectForKey:UIImagePickerControllerMediaURL]];
if (player)
{
/* Specify the URL that points to the movie file. */
[player setContentURL:[info objectForKey:
UIImagePickerControllerMediaURL]];
CGRect viewInsetRect = CGRectInset ([self.view bounds],
kMovieViewOffsetX,
kMovieViewOffsetY );
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:viewInsetRect];
[player view].backgroundColor = [UIColor lightGrayColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[self.view addSubview: [player view]];
[player prepareToPlay];
[player setCurrentPlaybackRate:0.5];
[player play];
}
// Register for the playback finished notification
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: #selector(myMovieFinishedCallback:)
name: MPMoviePlayerPlaybackDidFinishNotification
object: player];
}
}
My problem is the following: managing properly the app states.
I have several xibs implementing MPMoviePlayerViewcontroller. The light (that weight around 100kb) looping videos autoplay when the app comes back to the foreground (I've already handled the app states so that works fine).
In the 1st Xib the video plays immediately when coming back to the foreground. The 2nd Xib takes more time. The 3rd Xib takes even more time to continue autoplay and in the 4th Xib onwards it takes like 10 seconds to autoplay. When the app comes back from the the background to the foreground it takes a lot of time with a black screen until it starts auto play.As if one Xib affects the other.
I do the same code in every xib and as I advance it takes longer for the player continue auto play. Note that I overlay buttons above the player to go back or next. How to solve the lag explained previously?
AppDelegate.h
- (void)applicationWillResignActive:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"WillResignActive" object:nil];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"WillResignActive" object:nil];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"WillEnterForeGround" object:nil];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"DidBecomeActive" object:nil];
}
ViewController1.h
#synthesize playerController;
-(IBAction)next
{
two *back = [[two alloc]initWithNibName:#"two" bundle:Nil];
back.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:back animated:YES completion:nil ];
[back release];
}
- (void)viewDidLoad{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"mov"]];
playerController = [[MPMoviePlayerViewController alloc]initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:playerController];
[self.view insertSubview:playerController.view atIndex:0];
playerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
playerController.moviePlayer.controlStyle = MPMovieControlStyleNone;
playerController.moviePlayer.scalingMode = MPMovieScalingModeFill;
playerController.moviePlayer.repeatMode = MPMovieRepeatModeOne;
playerController.moviePlayer.view.userInteractionEnabled = NO;
playerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(AppDidBecomeActive) name:#"DidBecomeActive" object:nil];;
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(EnteredBackground) name:#"WillResignActive" object:nil];;
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(EnteredForeground) name:#"WillEnterForeGround" object:nil];;
[playerController.moviePlayer prepareToPlay];
[playerController.moviePlayer prepareToPlay];
[playerController.moviePlayer play];
}
-(void)AppDidBecomeActive{
if(playerController.moviePlayer.playbackState == MPMoviePlaybackStateInterrupted || playerController.moviePlayer.playbackState == MPMoviePlaybackStateStopped || playerController.moviePlayer.playbackState == MPMoviePlaybackStatePaused)
{
[playerController.moviePlayer play];
}
}
-(void)EnteredBackground
{ [playerController.moviePlayer pause];
}
-(void)EnteredForeground
{ [playerController.moviePlayer play];
}
I am trying out a simple camera app for practice. Was following these examples: iOS 6 App
and iOS 4 App
My code looks like this:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
UIButton *button;
UIImageView *imageView;
}
#property (nonatomic, retain) IBOutlet UIImageView *imageView;
- (IBAction)useCamera;
- (IBAction)useCameraRoll;
#end
ViewController.m
#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#interface ViewController ()
#end
#implementation ViewController
#synthesize imageView;
- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
// After saving iamge, dismiss camera
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
UIAlertView *alert;
// Unable to save the image
if (error)
alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Unable to save image to Photo Album."
delegate:self cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
else // All is well
alert = [[UIAlertView alloc] initWithTitle:#"Success"
message:#"Image saved to Photo Album."
delegate:self cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Access the uncropped image from info dictionary
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
// Save image
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (id)init
{
if (self = [super init])
{
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor grayColor];
// Button to activate camera
button = [[UIButton alloc] initWithFrame:CGRectMake(80, 55, 162, 53)];
[button setBackgroundImage:[UIImage imageNamed:#"Camera.png"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview:button];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)useCamera
{
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
- (IBAction)useCameraRoll
{
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
#end
My problem I like to access the camera from the app itself. What happens is that when i click useCamera button, it opens up the camera and take the image. Is it possible it could do that from the app itself? Sorry if it is a stupid question. Do point me out if I am doing something wrong.
Yes, use the UIImagePickerController class.
When the camera button is clicked, present an instance of UIImagePickerController. Also, since some iOS devices like the original iPad or some older iPod touches don't have cameras, I wouldn't recommend using separate buttons/methods for taking a new picture vs using one from the saved photos. Use one button and set its source type based on the device's capabilities using the available methods in the class. It may require rethinking your app's design, but it's also more likely to pass Apple's UI inspection, as they may not approve an app that has a button exclusively for taking a picture but can run on a device without a camera.
Once the user has either taken a new photo or chosen a photo from either the camera roll, use the imagePickerController:didFinishPickingMediaWithInfo: method from the UIImagePickerControllerDelegate class to pass the user's choice to your code.
Instances of UIImagePickerController are designed to be presented modally on all iOS devices when using the camera. Remember, as the name suggests, they are controllers and NOT views, so they shouldn't be used as subviews of UIView. While it may be possible to get creative with how you present it, you'll almost certainly have some side-effects and you'll further increase the chance that Apple will reject it. It only SEEMS like it's getting out the app to take the photo, but because you're presenting the controller from your app, it's still very much a part of it. Apple doesn't allow direct access to the camera hardware, which is exactly why they've created this class.
is this possible AVPlayer fetch music from ipodlibrary from MPMusicPlayerController and play ,since avplayer cannot access iPodMusicPlayer from MPMusicPlayerController , since AVPlayer support background playing and access to remoteEvents.
The code shown below is from addMusic project. so any help would be appreciated .Thank you
void audioRouteChangeListenerCallback (
void *inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueSize,
const void *inPropertyValue
) {
// ensure that this callback was invoked for a route change
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
// This callback, being outside the implementation block, needs a reference to the
// MainViewController object, which it receives in the inUserData parameter.
// You provide this reference when registering this callback (see the call to
// AudioSessionAddPropertyListener).
MainViewController *controller = (MainViewController *) inUserData;
// if application sound is not playing, there's nothing to do, so return.
if (controller.appSoundPlayer.playing == 0 ) {
NSLog (#"Audio route change while application audio is stopped.");
return;
} else {
// Determines the reason for the route change, to ensure that it is not
// because of a category change.
CFDictionaryRef routeChangeDictionary = inPropertyValue;
CFNumberRef routeChangeReasonRef =
CFDictionaryGetValue (
routeChangeDictionary,
CFSTR (kAudioSession_AudioRouteChangeKey_Reason)
);
SInt32 routeChangeReason;
CFNumberGetValue (
routeChangeReasonRef,
kCFNumberSInt32Type,
&routeChangeReason
);
// "Old device unavailable" indicates that a headset was unplugged, or that the
// device was removed from a dock connector that supports audio output. This is
// the recommended test for when to pause audio.
if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {
[controller.appSoundPlayer pause];
NSLog (#"Output device removed, so application audio was paused.");
UIAlertView *routeChangeAlertView =
[[UIAlertView alloc] initWithTitle: NSLocalizedString (#"Playback Paused", #"Title for audio hardware route-changed alert view")
message: NSLocalizedString (#"Audio output was changed", #"Explanation for route-changed alert view")
delegate: controller
cancelButtonTitle: NSLocalizedString (#"StopPlaybackAfterRouteChange", #"Stop button title")
otherButtonTitles: NSLocalizedString (#"ResumePlaybackAfterRouteChange", #"Play button title"), nil];
[routeChangeAlertView show];
// release takes place in alertView:clickedButtonAtIndex: method
} else {
NSLog (#"A route change occurred that does not require pausing of application audio.");
}
}
}
#implementation MainViewController
#synthesize artworkItem;
#synthesize userMediaItemCollection;
#synthesize playBarButton;
#synthesize pauseBarButton;
#synthesize musicPlayer;
#synthesize navigationBar;
#synthesize noArtworkImage; item has no associated artwork
#synthesize backgroundColorTimer;
#synthesize nowPlayingLabel;
#synthesize appSoundButton;
#synthesize addOrShowMusicButton;
#synthesize appSoundPlayer;
#synthesize soundFileURL;
#synthesize interruptedOnPlayback;
#synthesize playedMusicOnce;
#synthesize playing;
#implementation MainViewController
#synthesize artworkItem; // the now-playing media item's artwork image, displayed in the Navigation bar
#synthesize userMediaItemCollection; // the media item collection created by the user, using the media item picker
#synthesize playBarButton; // the button for invoking Play on the music player
#synthesize pauseBarButton; // the button for invoking Pause on the music player
#synthesize musicPlayer; // the music player, which plays media items from the iPod library
#synthesize navigationBar; // the application's Navigation bar
#synthesize noArtworkImage; // an image to display when a media item has no associated artwork
#synthesize backgroundColorTimer; // a timer for changing the background color -- represents an application that is
// doing something else while iPod music is playing
#synthesize nowPlayingLabel; // descriptive text shown on the main screen about the now-playing media item
#synthesize appSoundButton; // the button to invoke playback for the application sound
#synthesize addOrShowMusicButton; // the button for invoking the media item picker. if the user has already
// specified a media item collection, the title changes to "Show Music" and
// the button invokes a table view that shows the specified collection
#synthesize appSoundPlayer; // An AVAudioPlayer object for playing application sound
#synthesize soundFileURL; // The path to the application sound
#synthesize interruptedOnPlayback; // A flag indicating whether or not the application was interrupted during
// application audio playback
#synthesize playedMusicOnce; // A flag indicating if the user has played iPod library music at least one time
// since application launch.
#synthesize playing; // An application that responds to interruptions must keep track of its playing/
// not-playing state.
#pragma mark Music control
- (IBAction) AddMusicOrShowMusic: (id) sender {
// if the user has already chosen some music, display that list
if (userMediaItemCollection) {
MusicTableViewController *controller = [[MusicTableViewController alloc] initWithNibName: #"MusicTableView" bundle: nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController: controller animated: YES];
[controller release];
} else {
MPMediaPickerController *picker =
[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.allowsPickingMultipleItems = YES;
picker.prompt = NSLocalizedString (#"Add songs to play", "Prompt in media item picker");
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault animated: YES];
[self presentModalViewController: picker animated: YES];
[picker release];
}
}
- (void) updatePlayerQueueWithMediaCollection: (MPMediaItemCollection *) mediaItemCollection {
// Configure the music player, but only if the user chose at least one song to play
if (mediaItemCollection) {
if (userMediaItemCollection == nil) {
[self setUserMediaItemCollection: mediaItemCollection];
[musicPlayer setQueueWithItemCollection: userMediaItemCollection];
[self setPlayedMusicOnce: YES];
[musicPlayer play];
} else {
BOOL wasPlaying = NO;
if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
wasPlaying = YES;
}
MPMediaItem *nowPlayingItem = musicPlayer.nowPlayingItem;
NSTimeInterval currentPlaybackTime = musicPlayer.currentPlaybackTime;
NSMutableArray *combinedMediaItems = [[userMediaItemCollection items] mutableCopy];
NSArray *newMediaItems = [mediaItemCollection items];
[combinedMediaItems addObjectsFromArray: newMediaItems];
[self setUserMediaItemCollection: [MPMediaItemCollection collectionWithItems: (NSArray *) combinedMediaItems]];
[combinedMediaItems release];
[musicPlayer setQueueWithItemCollection: userMediaItemCollection];
musicPlayer.nowPlayingItem = nowPlayingItem;
musicPlayer.currentPlaybackTime = currentPlaybackTime;
if (wasPlaying) {
[musicPlayer play];
}
}
navigationBar.topItem.leftBarButtonItem.enabled = YES;
[addOrShowMusicButton setTitle: NSLocalizedString (#"Show Music", #"Alternate title for 'Add Music' button, after user has chosen some music")
forState: UIControlStateNormal];
}
}
- (void) restorePlaybackState {
if (musicPlayer.playbackState == MPMusicPlaybackStateStopped && userMediaItemCollection) {
[addOrShowMusicButton setTitle: NSLocalizedString (#"Show Music", #"Alternate title for 'Add Music' button, after user has chosen some music")
forState: UIControlStateNormal];
if (playedMusicOnce == NO) {
[self setPlayedMusicOnce: YES];
[musicPlayer play];
}
}
}
#pragma mark Media item picker delegate methods________
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection {
[self dismissModalViewControllerAnimated: YES];
[self updatePlayerQueueWithMediaCollection: mediaItemCollection];
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackOpaque animated: YES];
}
- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker {
[self dismissModalViewControllerAnimated: YES];
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackOpaque animated: YES];
}
#pragma mark Music notification handlers__________________
- (void) handle_NowPlayingItemChanged: (id) notification {
MPMediaItem *currentItem = [musicPlayer nowPlayingItem];
UIImage *artworkImage = noArtworkImage;
MPMediaItemArtwork *artwork = [currentItem valueForProperty: MPMediaItemPropertyArtwork];
// Obtain a UIImage object from the MPMediaItemArtwork object
if (artwork) {
artworkImage = [artwork imageWithSize: CGSizeMake (30, 30)];
}
// Obtain a UIButton object and set its background to the UIImage object
UIButton *artworkView = [[UIButton alloc] initWithFrame: CGRectMake (0, 0, 30, 30)];
[artworkView setBackgroundImage: artworkImage forState: UIControlStateNormal];
// Obtain a UIBarButtonItem object and initialize it with the UIButton object
UIBarButtonItem *newArtworkItem = [[UIBarButtonItem alloc] initWithCustomView: artworkView];
[self setArtworkItem: newArtworkItem];
[newArtworkItem release];
[artworkItem setEnabled: NO];
[navigationBar.topItem setRightBarButtonItem: artworkItem animated: YES];
[nowPlayingLabel setText: [
NSString stringWithFormat: #"%# %# %# %#",
NSLocalizedString (#"Now Playing:", #"Label for introducing the now-playing song title and artist"),
[currentItem valueForProperty: MPMediaItemPropertyTitle],
NSLocalizedString (#"by", #"Article between song name and artist name"),
[currentItem valueForProperty: MPMediaItemPropertyArtist]]];
if (musicPlayer.playbackState == MPMusicPlaybackStateStopped) {
[nowPlayingLabel setText: [
NSString stringWithFormat: #"%#",
NSLocalizedString (#"Music-ended Instructions", #"Label for prompting user to play music again after it has stopped")]];
}
}
- (void) handle_PlaybackStateChanged: (id) notification {
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if (playbackState == MPMusicPlaybackStatePaused) {
navigationBar.topItem.leftBarButtonItem = playBarButton;
} else if (playbackState == MPMusicPlaybackStatePlaying) {
navigationBar.topItem.leftBarButtonItem = pauseBarButton;
} else if (playbackState == MPMusicPlaybackStateStopped) {
navigationBar.topItem.leftBarButtonItem = playBarButton;
// Even though stopped, invoking 'stop' ensures that the music player will play
// its queue from the start.
[musicPlayer stop];
}
}
- (void) handle_iPodLibraryChanged: (id) notification {
]
}
#pragma mark Application playback control_________________
- (IBAction) playAppSound: (id) sender {
[appSoundPlayer play];
playing = YES;
[appSoundButton setEnabled: NO];
}
- (void) alertView: routeChangeAlertView clickedButtonAtIndex: buttonIndex {
if ((NSInteger) buttonIndex == 1) {
[appSoundPlayer play];
} else {
[appSoundPlayer setCurrentTime: 0];
[appSoundButton setEnabled: YES];
}
[routeChangeAlertView release];
}
#pragma mark AV Foundation delegate methods____________
- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) appSoundPlayer successfully: (BOOL) flag {
playing = NO;
[appSoundButton setEnabled: YES];
}
- (void) audioPlayerBeginInterruption: player {
NSLog (#"Interrupted. The system has paused audio playback.");
if (playing) {
playing = NO;
interruptedOnPlayback = YES;
}
}
- (void) audioPlayerEndInterruption: player {
NSLog (#"Interruption ended. Resuming audio playback.");
[[AVAudioSession sharedInstance] setActive: YES error: nil];
if (interruptedOnPlayback) {
[appSoundPlayer prepareToPlay];
[appSoundPlayer play];
playing = YES;
interruptedOnPlayback = NO;
}
}
#pragma mark Table view delegate methods
- (void) musicTableViewControllerDidFinish: (MusicTableViewController *) controller {
[self dismissModalViewControllerAnimated: YES];
[self restorePlaybackState];
}
#pragma mark Application setup
- (void) setupApplicationAudio {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"sound"
ofType: #"caf"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL;
[newURL release];
[[AVAudioSession sharedInstance] setDelegate: self];
// [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 0;
AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof (doSetProperty),
&doSetProperty
);
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
// Instantiates the AVAudioPlayer object, initializing it with the sound
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
}
- (void) registerForMediaPlayerNotifications {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver: self
selector: #selector (handle_NowPlayingItemChanged:)
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[notificationCenter addObserver: self
selector: #selector (handle_PlaybackStateChanged:)
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[musicPlayer beginGeneratingPlaybackNotifications];
}
- (BOOL) useiPodPlayer {
if ([[NSUserDefaults standardUserDefaults] boolForKey: PLAYER_TYPE_PREF_KEY]) {
return YES;
} else {
return NO;
}
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
[self togglePlayPause];
break;
case UIEventSubtypeRemoteControlPlay:
[self playAudio];
break;
case UIEventSubtypeRemoteControlPause:
[self pauseAudio];
break;
default:
break;
}
}
}
- (IBAction) playOrPauseMusic: (id)sender {
[self togglePlayPause];
}
- (void)playAudio {
[musicPlayer play];
}
- (void)pauseAudio {
[musicPlayer pause];
}
- (void)togglePlayPause {
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {
[musicPlayer play];
} else if (playbackState == MPMusicPlaybackStatePlaying) {
[musicPlayer pause];
}
}
// Configure the application.
- (void) viewDidLoad {
[super viewDidLoad];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self setupApplicationAudio];
[self setPlayedMusicOnce: NO];
[self setNoArtworkImage: [UIImage imageNamed: #"no_artwork.png"]];
[self setPlayBarButton: [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemPlay
target: self
action: #selector (playOrPauseMusic:)]];
[self setPauseBarButton: [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemPause
target: self
action: #selector (playOrPauseMusic:)]];
[addOrShowMusicButton setTitle: NSLocalizedString (#"Add Music", #"Title for 'Add Music' button, before user has chosen some music")
forState: UIControlStateNormal];
[appSoundButton setTitle: NSLocalizedString (#"Play App Sound", #"Title for 'Play App Sound' button")
forState: UIControlStateNormal];
[nowPlayingLabel setText: NSLocalizedString (#"Instructions", #"Brief instructions to user, shown at launch")];
if ([self useiPodPlayer]) {
[self setMusicPlayer: [MPMusicPlayerController iPodMusicPlayer]];
if ([musicPlayer nowPlayingItem]) {
navigationBar.topItem.leftBarButtonItem.enabled = YES;
[self handle_NowPlayingItemChanged: nil];
if ([musicPlayer playbackState] == MPMusicPlaybackStatePaused) {
navigationBar.topItem.leftBarButtonItem = playBarButton;
}
}
} else {
[self setMusicPlayer: [MPMusicPlayerController applicationMusicPlayer]];
[musicPlayer setShuffleMode: MPMusicShuffleModeOff];
[musicPlayer setRepeatMode: MPMusicRepeatModeNone];
}
[self registerForMediaPlayerNotifications];
[self setBackgroundColorTimer: [NSTimer scheduledTimerWithTimeInterval: 3.5
target: self
selector: #selector (updateBackgroundColor)
userInfo: nil
repeats: YES]];
}
// Invoked by the backgroundColorTimer.
- (void) updateBackgroundColor {
[UIView beginAnimations: nil context: nil];
[UIView setAnimationDuration: 3.0];
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
self.view.backgroundColor = [UIColor colorWithRed: redLevel
green: greenLevel
blue: blueLevel
alpha: 1.0];
[UIView commitAnimations];
}
#pragma mark Application state management_____________
- (void) didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void) viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[musicPlayer endGeneratingPlaybackNotifications];
[musicPlayer release];
[artworkItem release];
[backgroundColorTimer invalidate];
[backgroundColorTimer release];
[navigationBar release];
[noArtworkImage release];
[nowPlayingLabel release];
[pauseBarButton release];
[playBarButton release];
[soundFileURL release];
[userMediaItemCollection release];
[super dealloc];
}
#end
These four lines should get you started :)
MPMediaItem *nowPlayingItem = musicPlayer.nowPlayingItem;
NSURL * mediaURL = [nowPlayingItem valueForProperty:MPMediaItemPropertyAssetURL];
AVPlayerItem * myAVPlayerItem = [AVPlayerItem playerItemWithURL:mediaURL];
AVPlayer * myAvPlayer = [AVPlayer playerWithPlayerItem:myAVPlayerItem];
iam developing one application.In that i need to get the music files from the phone library.For that iam using the MPMediaPickerCOntroller.But it doesn't fire the didpickingitem delegate method.My code like below.
- (void)viewDidLoad
{
[super viewDidLoad];
MPMediaPickerController *picker =[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.allowsPickingMultipleItems = YES;
picker.prompt =#"Add songs to play";
[self presentModalViewController:picker animated: YES];
}
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
NSLog(#"sdfadsf");
NSLog(#"%#",mediaItemCollection);
NSArray *slist=[mediaItemCollection copy];
NSLog(#"%#",slist);
}
Do you declare the MPMediaPickerControllerDelegate in your .h?
ex:
#interface FirstViewController : UIViewController
If you do not that would explain why the method isn't firing. Also, I do not believe it will work on the simulator; only on devices.
EDIT:
-(IBAction)presentLibrary:(id)sender
{
//this is called from a button press, but you could do it in viewDidLoad
MPMediaPickerController *picker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.allowsPickingMultipleItems = NO;
picker.prompt = NSLocalizedString (#"Select any song from the list", #"Prompt to user to choose some songs to play");
[self presentModalViewController: picker animated: YES];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
NSLog(#"didpick");
if (mediaItemCollection) {
[_mediaPlayer setQueueWithItemCollection: mediaItemCollection];
_mediaCollection = mediaItemCollection;
}
[mediaPicker dismissModalViewControllerAnimated:YES];
}
Read from here The Music Player Framework in iPhone