Multimedia playback for iOS development

Source: Internet
Author: User
Tags file url

Ios sdk provides many convenient methods to play multimedia. This article uses these sdks for 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 below RegistrationCode:

# Import <Audiotoolbox/Audiotoolbox. h>
@ InterfaceMediaplayerviewcontroller: uiviewcontroller
{
Iboutlet uibutton*Audiobutton;
Systemsoundid audio sound;
}
 -  (  ID  ) Init
{
Self = [Super initwithnibname: @" Mediaplayerviewcontroller " Bundle: Nil];
If (Self ){
// Get the full path of sound12.aif
Nsstring * Soundpath = [[Nsbundle mainbundle] pathforresource: @" Sound12 "
Oftype: @" AIF " ];
// If this file is actually in the bundle...
If (Soundpath ){
// Create a File URL with this path
Nsurl * Soundurl = [Nsurl fileurlwithpath: soundpath];

// Register sound file located at that URL as a system sound
Osstatus err = Audioservicescreatesystemsoundid (cfurlref) soundurl,
& Audio Sound );
If (Err ! = Kaudioservicesnoerror)
Nslog ( @" Cocould not load % @, error code: % d " , Soundurl, err );
}
}
Return Self;
}

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

-(Ibaction) playdesksound :(ID) Sender
{
Audioservicesplaysystemsound (audio sound );
}

Use the following code to add a vibration effect:

 
-(Ibaction) playdesksound :(ID) Sender
{
Audioservicesplaysystemsound (audio sound );
Audioservicesplaysystemsound (ksystemsoundid_vibrate );
}

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:

 #import       avfoundation  /  avfoundation. h  >  
@ interface mediaplayerviewcontroller: uiviewcontroller avaudioplayerdelegate >
{< br> iboutlet uibutton * audiobutton;
systemsoundid audio sound;
avaudioplayer * audioplayer;

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

 -  (  ID  ) Init
{
Self = [Super initwithnibname: @" Mediaplayerviewcontroller " Bundle: Nil];

If (Self ){

Nsstring * Musicpath = [[Nsbundle mainbundle] pathforresource: @" Music "
Oftype: @" MP3 " ];
If (Musicpath ){
Nsurl * Musicurl = [Nsurl fileurlwithpath: musicpath];
Audioplayer = [[Avaudioplayer alloc] initwithcontentsofurl: musicurl
Error: Nil];
[Audioplayer setdelegate: Self];
}
Nsstring * Soundpath = [[Nsbundle mainbundle] pathforresource: @" Sound12 "
Oftype: @" AIF " ];

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

 -  (Ibaction) playaudiofile :(  ID  ) Sender
{
If ([Audioplayer isplaying]) {
// Stop playing audio and change text of Button
[Audioplayer stop];
[Sender settitle: @" Play audio file "
Forstate: uicontrolstatenormal];
}
Else {
// Start playing audio and change text of button so
// User can tap to stop playback
[Audioplayer play];
[Sender settitle: @" Stop audio file "
Forstate: uicontrolstatenormal];
}
}

Run ourProgramTo play the music.

Corresponding to this classAvaudioplayerdelegateThere are 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.

-(Void) Audioplayerdidfinishplaying :( avaudioplayer*) Player
Successfully :( bool) Flag
{
[Audiobutton settitle:@"Play audio file"
Forstate: uicontrolstatenormal];
}

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.

-(Void) Audioplayerendinterruption :( avaudioplayer*) Player
{
[Audioplayer play];
}

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.

• H.264 (baseline profile level 264)
• 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. In your application, add this reference first, and then modifyMediaplayerviewcontroller.H file.

# Import <Mediaplayer/Mediaplayer. h>
@ InterfaceMediaplayerviewcontroller: uiviewcontroller<Avaudioplayerdelegate>
{
Mpmovieplayercontroller*Movieplayer;

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

 -  ( ID  ) Init
{
Self = [Super initwithnibname: @" Mediaplayerviewcontroller " Bundle: Nil];
If (Self ){

Nsstring * Moviepath = [[Nsbundle mainbundle] pathforresource: @" Layers "
Oftype: @" M4v " ];
If (Moviepath ){
Nsurl * Movieurl = [Nsurl fileurlwithpath: moviepath];
Movieplayer = [[Mpmovieplayercontroller alloc]
Initwithcontenturl: movieurl];
}

Mpmovieplayercontroller has a view to display the player control. In the viewdidload method, we will display the player.

 -  (  void  ) viewdidload 
{< br> [[self view] addsubview: [movieplayer view];
float halfheight = [[self view] bounds]. size. height / 2.0 ;
float width = [[self view] bounds]. size. width;
[[movieplayer view] setframe: cgrectmake ( 0 , halfheight, width, halfheight)];
}

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

 
Mpmovieplayerviewcontroller*Playerviewcontroller=
[[Mpmovieplayerviewcontroller alloc] initwithcontenturl: movieurl];
[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:

If(Musicpath ){
Nsurl*Musicurl=[Nsurl fileurlwithpath: musicpath];
[[Avaudiosession sharedinstance]
Setcategory: avaudiosessioncategoryplayback error: Nil];
Audioplayer=[[Avaudioplayer alloc] initwithcontentsofurl: musicurl
Error: Nil];
[Audioplayer setdelegate: Self];
}

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

Summary:This article describes in detail the classes used to play audio files in the ios sdk through examples,ArticleThe code in this article will be available for download later.

code: http://files.cnblogs.com/zhuqil/MediaPlayer.zip

Related Article

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.