Wednesday, April 18, 2012

AVFoundation Framework

iPhone has a rich support of media and in this post I will discuss about how to play a .mp3 file in iPhone.

Design Phase: In this example I will have three objects of UIButton class for play, pause and stop the music, I will have an object of UISlider with the help of which I will control the volume and a UIProgressView object which will keep on updating its value, here's how our final output will look like



Step 1: Open Xcode select windows based application and give an appropriate name to your project now add UIViewController subclass file to your project and give them the name MyviewController so now you will get two files that's MyviewController.h and MyviewController.m.

Since we are going to play a .mp3 file we have to import a framework called as AVFoundation Framework (Audio video foundation framework) and here's how will you do that
  1. Select target present in Groups &File now you will see a file whose name is same like your project name, now right click that file and select Get Info the entire scene will look like this



  2. Now a window will open which will show the total number of frameworks present in your project



    Now just hit the add button so that you can get the list of the frameworks that you can use and that list looks like this



  3. just select AVFoundation framework press the add button and your done, now you will be seeing the AVFoundation framework in your Groups &files.

  4. Now Go to the MyviewController.h file and add this piece of code 

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>


@interface MyviewController : UIViewController {

UIButton *playButton,*pauseButton,*stopButton;
UILabel *Volumelabel;
UISlider *myslider;
AVAudioPlayer *audioPlayer;
NSTimer *timer;
UIProgressView *myprogressview;
}
-(void)playMusic;        //play Music
-(void)pauseMusic;     //pause music
-(void)stopMusic;       //stop music
-(void) volumeControl;  //volume control
-(void)updateProgress;  //update progress view
@end

The above code contains 5 functions which are explained in the comments itself

Step 2: now select the MyviewController.m file and select its init method where we will set the frame and perform some initial settings for all the objects of the class that we have used in the .h file add this piece of code.



But wait we have not added a .mp3 file yet, so in order to add a .mp3 file here are the steps that you have to follow
  1. Search for an .mp3 file and copy it in the desktop, now go to Xcode and select the resource folder right click it and select add existing items.



  2. Now select the .mp3 file from the desktop and add it to your project but before that a dialog will pop up which looks like this



  3. This dialog box says that it will make a copy of the selected file in your resource so in case if you delete the actual file it will not affect your project because a copy of it will always be present in your Groups & files.

Now we will set the frames and text of the controls that we have


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization

//setting the labels
Volumelabel = [[UILabel alloc]initWithFrame:CGRectMake(1072095821)];
Volumelabel.text = @"Volume";
[Volumelabel setBackgroundColor:[UIColor blackColor]];
Volumelabel.textColor = [UIColor whiteColor];
//setting for the buttons
playButton = [UIButton buttonWithType:UIButtonTypeCustom];
[playButton setFrame:CGRectMake(201387247)];
[playButton setBackgroundImage:[UIImage imageNamed:@"playbutton.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:@selector(playMusic) forControlEvents:UIControlEventTouchUpInside];
pauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pauseButton setFrame:CGRectMake(201827247)];
[pauseButton setBackgroundImage:[UIImage imageNamed:@"pause_button.png"] forState:UIControlStateNormal];
[pauseButton addTarget:self action:@selector(pauseMusic) forControlEvents:UIControlEventTouchUpInside];
stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
[stopButton setFrame:CGRectMake(202277247)];
[stopButton setBackgroundImage:[UIImage imageNamed:@"stop.png"] forState:UIControlStateNormal];
[stopButton addTarget:self action:@selector(stopMusic) forControlEvents:UIControlEventTouchUpInside];
//settings for the slider
myslider = [[UISlider alloc]initWithFrame:CGRectMake(10822815923)];
myslider.minimumValue = 0.0;
myslider.maximumValue = 1.0;
[myslider addTarget:self action:@selector(volumeControl) forControlEvents:UIControlEventValueChanged];
//storing the file location in the object of NSData
NSData *filelocation = [[NSData alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"wake" ofType:@"mp3"]];
//suppling the file address to the object of AVAudioPlayer class
audioPlayer = [[AVAudioPlayer alloc]initWithData:filelocation error:nil];
//setting the progress view
myprogressview = [[UIProgressView alloc]initWithFrame:CGRectMake(112179150,9)];
//setting the back color for the view
[self.view setBackgroundColor:[UIColor blackColor]];
    }
    return self;
}


Step 3: now select the load view method and add these objects to the current view in the loadView method


- (void)loadView {
[super loadView];
[self.view addSubview:playButton];
[self.view addSubview:pauseButton];
[self.view addSubview:stopButton];
[self.view addSubview:myslider];
[self.view addSubview:myprogressview];
[self.view addSubview:Volumelabel];
}

Step 4: now its time to give those functions some body so I will explain each function one by one


-(void)playMusic
{
[audioPlayer play];
//Updating the progress view
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(updateProgressuserInfo:nil repeats:YES];
[timer fire];
}

-(void)pauseMusic
{
//pause the music player
[audioPlayer pause];
}

-(void)stopMusic
{
//stop the music player
[audioPlayer stop];
audioPlayer.currentTime = 0.0;
}

-(void) volumeControl
{
audioPlayer.volume = [myslider value];

}

-(void)updateProgress 
{
float x= audioPlayer.currentTime/audioPlayer.duration;
myprogressview.progress = x;
}


    Step 5: go to the appDelegate file and add the current view to the window and run the application that's all here's how you will do that



    #import "AVFoundationDemoAppDelegate.h"
    #import "MyviewController.h"

    @implementation AVFoundationDemoAppDelegate

    @synthesize window;


    - (void)applicationDidFinishLaunching:(UIApplication *)application {    

        // Override point for customization after application launch
    MyviewController * obj = [[MyviewController alloc]init];
    [window addSubview:obj.view];
        [window makeKeyAndVisible];
    }


    Press Build and Go and that's all, you will get the following output




    Now hit the play button and listen to the song
    I hope this post helped you, Happy iCoding

    No comments:

    Post a Comment