Search This Blog

Showing posts with label How to play audio and video in iPhone ?. Show all posts
Showing posts with label How to play audio and video in iPhone ?. Show all posts

Jul 28, 2011

How to play audio and video in iPhone ?

This code is show how to play audio and video files in iPhone SDK.


You can download source code from here Download.

1. Code for .h file.


#import
#import
#import

@interface MultiMediaViewController : UIViewController {

    MPMoviePlayerViewController *player;
    AVAudioPlayer *audioPlayer;
}

- (IBAction)btnPlayVideo_Clicked:(id)sender;
- (IBAction)btnPlayAudio_Clicked:(id)sender;
- (IBAction)btnPlayBackgroundAudio_Clicked:(id)sender;
- (IBAction)btnStopAudio_Clicked:(id)sender;

@end


2. Code for .m file.

#import "MultiMediaViewController.h"


@implementation MultiMediaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
}

- (IBAction)btnPlayVideo_Clicked:(id)sender
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"mp4" inDirectory:nil];
    NSURL *movieURL = [NSURL fileURLWithPath:path];
    player= [[ MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
    [self presentMoviePlayerViewControllerAnimated:player];
}

- (void)mediaPlayerPlaybackDidFinish:(id)sender
{   
    [player.moviePlayer stop];
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)btnPlayAudio_Clicked:(id)sender
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"mp3" inDirectory:nil];
    NSURL *audioURL = [NSURL fileURLWithPath:path];
    player= [[ MPMoviePlayerViewController alloc] initWithContentURL:audioURL];
    [self presentMoviePlayerViewControllerAnimated:player];
}

- (IBAction)btnPlayBackgroundAudio_Clicked:(id)sender
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"mp3" inDirectory:nil];
    NSURL *audioURL = [NSURL fileURLWithPath:path];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
    audioPlayer.numberOfLoops = -1;
    [audioPlayer play];
}

- (IBAction)btnStopAudio_Clicked:(id)sender
{
    [audioPlayer stop];
}

- (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 {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end