Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

iOS Audio and Video


May 21, 2021 iOS Development Manual


Table of contents


IOS Audio and Video


Brief introduction

Audio and video are common on the latest devices.

Adding iosAVFoundation.framework and MediaPlayer.framework to the Xcode project allows IOS to support audio and video.

The instance step

1, create a simple View base application

2, select the project file, select the target, and then add AVFoundation.framework and MediaPlayer.framework

3. Add two buttons to ViewController.xib to create an action for playing audio and video separately

4, update ViewController.h, as shown below

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

@interface ViewController : UIViewController
{
    AVAudioPlayer *audioPlayer;
    MPMoviePlayerViewController *moviePlayer;
    
}
-(IBAction)playAudio:(id)sender;
-(IBAction)playVideo:(id)sender;
@end

5, update the ViewController .m, as shown below

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

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

- (void)didReceiveMemoryWarning
{
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}
-(IBAction)playAudio:(id)sender{
   NSString *path = [[NSBundle mainBundle]
   pathForResource:@"audioTest" ofType:@"mp3"];
   audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:
   [NSURL fileURLWithPath:path] error:NULL];
   [audioPlayer play];
}
-(IBAction)playVideo:(id)sender{
   NSString *path = [[NSBundle mainBundle]pathForResource:
   @"videoTest" ofType:@"mov"];
   moviePlayer = [[MPMoviePlayerViewController 
   alloc]initWithContentURL:[NSURL fileURLWithPath:path]];
   [self presentModalViewController:moviePlayer animated:NO];
}
@end

Note the item

Audio and video files need to be added to ensure the expected output

Output

Run the program and the output is as follows

iOS Audio and Video

When we click play video (play video) it appears as follows:

iOS Audio and Video