Learn about multimedia playback in iOS development

Source: Internet
Author: User

IOS developmentOfMultimediaPlaying is the content to be introduced in this article,IOS SDKProvides a lot of convenient methods to play multimedia. This article will use theseSDKMake a demo to show you how to use them to play audio files.

AudioToolbox framework

Use AudioToolbox framework. This framework can register short voices to the system sound service. The sound registered to the system sound service is called system sounds. It must meet the following conditions.

1. the playback time cannot exceed 30 seconds

2. The data must be in PCM or IMA4 stream format.

3. It must be packaged into one of the following three formats: Core Audio Format (. caf), Waveform audio (.wav), or Audio Interchange File (. aiff)

Sound files must be placed under the Local folder of the device. Use the AudioServicesCreateSystemSoundID method to register this sound file. AudioServicesCreateSystemSoundID requires the CFURLRef object of the url of the sound file. See the following registration code:

 
 
  1. #import <AudioToolbox/AudioToolbox.h> 
  2. @interface MediaPlayerViewController : UIViewController{      
  3. IBOutlet UIButton *audioButton;      
  4. SystemSoundID shortSound;}- (id)init{      
  5. self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];      
  6. if (self) {          
  7. // Get the full path of Sound12.aif          
  8. NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"    
  9.                                               ofType:@"aif"];          
  10. // If this file is actually in the bundle...         
  11.  if (soundPath) {              
  12.  // Create a file URL with this path             
  13.   NSURL *soundURL = [NSURL fileURLWithPath:soundPath];   
  14. // Register sound file located at that URL as a system sound             
  15.  OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL,    
  16.                                       &shortSound);              
  17.        if (err != kAudioServicesNoError)                 
  18.         NSLog(@"Could not load %@, error code: %d", soundURL, err);  
  19.     }      
  20.   }     
  21. return self;  

In this way, you can use the following code to play the sound:

 
 
  1. - (IBAction)playShortSound:(id)sender{    AudioServicesPlaySystemSound(shortSound);} 

Use the following code to add a vibration effect:

 
 
  1. - (IBAction)playShortSound:(id)sender{      
  2. AudioServicesPlaySystemSound(shortSound);      
  3. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);}  
  4. AVFoundation framework 

You can use the AVAudioPlayer class to compress Audio files that have been compressed or that have been used for more than 30 seconds. This class is defined in AVFoundation framework.

Below we use this class to play an mp3 audio file. First introduce the AVFoundation framework, and then add the following code in MediaPlayerViewController. h:

 
 
  1. #import <AVFoundation/AVFoundation.h> 
  2. @interface MediaPlayerViewController : UIViewController <AVAudioPlayerDelegate>{  
  3.     IBOutlet UIButton *audioButton;      
  4.     SystemSoundID shortSound;      
  5.     AVAudioPlayer *audioPlayer; 

The AVAudioPlayer class also needs to know the path of the audio file. Use the following code to create an AVAudioPlayer instance:

 
 
  1. - (id)init{  
  2.     self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];  
  3.       if (self) {  
  4.                   NSString *musicPath = [[NSBundle mainBundle]  pathForResource:@"Music"     
  5.         ofType:@"mp3"];          
  6.       if (musicPath) {   
  7.                  NSURL *musicURL = [NSURL fileURLWithPath:musicPath];  
  8.                audioPlayer = [[AVAudioPlayer alloc]  initWithContentsOfURL:musicURL     
  9.                       error:nil];   
  10.                [audioPlayer setDelegate:self];        
  11.     }          
  12.     NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"      
  13.  ofType:@"aif"]; 

We can start playing this mp3 file in a button click event, such:

 
 
  1. - (IBAction)playAudioFile:(id)sender{  
  2.     if ([audioPlayer isPlaying]) {  
  3.             // Stop playing audio and change text of button  
  4.               [audioPlayer stop];          
  5.               [sender setTitle:@"Play Audio File"   
  6.               forState:UIControlStateNormal];  
  7.     }    else {         
  8.     // Start playing audio and change text of button so    
  9.     // user can tap to stop playback    
  10.     [audioPlayer play];          
  11.     [sender setTitle:@"Stop Audio File"     
  12.     forState:UIControlStateNormal];  
  13.    }  

In this way, we can run our program to play music.

AVAudioPlayerDelegate corresponding to this class has two delegate methods. One is audioPlayerDidFinishPlaying: successfully: triggered after the audio is played completely. After the playback is complete, you can reset the text of the playback button to Play Audio File.

 
 
  1. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player   
  2.                       successfully:(BOOL)flag  
  3.               {      
  4.            [audioButton setTitle:@"Play Audio File"  
  5.                             forState:UIControlStateNormal];  
  6.             } 

AudioPlayerEndInterruption: triggered when the program is interrupted by the application and returned to the application. Here, when you return to this application, continue playing music.

 
 
  1. - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player{    [audioPlayer play];}  
  2. MediaPlayer framework 

Play a movie file:

In iOS sdk, you can use MPMoviePlayerController to play movie files. However, there are strict format requirements for playing movie files on iOS devices. Only the following two formats of movie files can be played.

 
 
  1. • H.264 (Baseline Profile Level 3.0)  
  2. • MPEG-4 Part 2 video (Simple Profile) 

Fortunately, you can use iTunes to convert the file to the above two formats.

MPMoviePlayerController can also play video files on the Internet. However, we recommend that you first download the video file to your local computer and then play it back. If you do not, iOS may refuse to play large video files.

This class is defined in MediaPlayer framework. Add this reference in your application, and then modify the MediaPlayerViewController. h file.

 
 
  1. #import <MediaPlayer/MediaPlayer.h> 
  2. @interface MediaPlayerViewController : UIViewController <AVAudioPlayerDelegate> 
  3. {    
  4.   MPMoviePlayerController *moviePlayer; 

Next we will use this class to play a. m4v video file. Similar to the previous one, a url path is required.

 
 
  1. - (id)init{     
  2.  self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];  
  3.     if (self) {            NSString *moviePath = [[NSBundle mainBundle]   
  4.     pathForResource:@"Layers"       
  5.     ofType:@"m4v"  
  6.   ];         
  7.    if (moviePath) {            
  8.      NSURL *movieURL = [NSURL fileURLWithPath:moviePath];              
  9.      moviePlayer = [[MPMoviePlayerController alloc]                                       
  10.      initWithContentURL:movieURL];          
  11.  } 

MPMoviePlayerController has a view to display the player control. In the viewDidLoad method, we will display the player.

 
 
  1. - (void)viewDidLoad{      
  2. [[self view] addSubview:[moviePlayer view]];  
  3.     float halfHeight = [[self view] bounds].size.height / 2.0;  
  4.     float width = [[self view] bounds].size.width;      
  5.     [[moviePlayer view] setFrame:CGRectMake(0, halfHeight, width, halfHeight)];  
  6.  } 

There is also an MPMoviePlayerViewController class used to play video files in full screen mode. Its usage is the same as that of MPMoviePlayerController.

 
 
  1. MPMoviePlayerViewController *playerViewController =  
  2.     [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];    
  3. [viewController presentMoviePlayerViewControllerAnimated:playerViewController]; 

When we listen to music, we can use the iphone to do other things. In this case, the player can also run in the background. We only need to make simple settings in the application.

1. Add a Required background modes node in the Info property list, which is an array and sets the first item to set App plays audio.

2. Add the following code to the mp3 player code:

 
 
  1. if (musicPath) {          
  2. NSURL *musicURL = [NSURL fileURLWithPath:musicPath];          
  3. [[AVAudioSession sharedInstance]                     
  4.            setCategory:AVAudioSessionCategoryPlayback error:nil];          
  5. audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL     
  6.                                error:nil];          
  7.        [audioPlayer setDelegate:self];  

The function of playing music in the background cannot be seen in the simulator, but only on the real machine.

Summary: UnderstandingIOS developmentOfMultimediaThe playback content has been introduced. This article explains in detail through examples.IOS SDKClass used to play audio files. Finally, I hope this article will help you! This article provides code for friends to easily learn, code: http://files.cnblogs.com/zhuqil/MediaPlayer.zip

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.