A simple example of how to play sound and music functions in IOS app _ios

Source: Internet
Author: User
Tags file url

Play sound
the ability to play sound effects may be encountered during iOS development
In fact very simple, iOS has provided a framework for directly responsible for playing sound audiotoolbox.framework
New Project Testwechatsounds

Import Audiotoolbox.framework to a new project

After the import succeeds the following figure

The project directory is as follows

Next we add several CAF-formatted audio files to the project

Next we open the project default generated Viewcontroller to add code
Import Audiotoolbox

Copy Code code as follows:

#import <AudioToolbox/AudioToolbox.h>

Add button to view to play sound after clicking
Copy Code code as follows:

-(void) Viewdidload {
[Super Viewdidload];
Do no additional setup after loading the view, typically from a nib.

UIButton *btn1=[[uibutton Alloc] Initwithframe:cgrectmake (20, 100, 120, 36)];
[Btn1 Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];
[Btn1 settitle:@ "Warning" forstate:uicontrolstatenormal];
[Btn1 addtarget:self Action: @selector (Btn1act) forcontrolevents:uicontroleventtouchupinside];
[Self.view ADDSUBVIEW:BTN1];

UIButton *btn2=[[uibutton Alloc] Initwithframe:cgrectmake (20, 150, 120, 36)];
[Btn2 Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];
[Btn2 settitle:@ "error" forstate:uicontrolstatenormal];
[Btn2 addtarget:self Action: @selector (Btn2act) forcontrolevents:uicontroleventtouchupinside];
[Self.view ADDSUBVIEW:BTN2];
}

Achieve playback effects
Copy Code code as follows:

-(void) Btn1act {

[Self playsoundeffect:@ "ALARM.CAF"];
}
-(void) Btn2act {

[Self playsoundeffect:@ "CT-ERROR.CAF"];
}

-(void) Playsoundeffect: (NSString *) name{
NSString *audiofile=[[nsbundle Mainbundle] Pathforresource:name Oftype:nil];
Nsurl *fileurl=[nsurl Fileurlwithpath:audiofile];
1. Get System sound ID
Systemsoundid soundid=0;
/**
* Infileurl: Audio file URL
* Outsystemsoundid: Sound ID (This function adds the sound file to the System Audio service and returns a long shaping ID)
*/
Audioservicescreatesystemsoundid ((__bridge cfurlref) (FILEURL), &soundid);
If you need to perform some action after playback, you can call the following method to register a playback completion callback function
Audioservicesaddsystemsoundcompletion (soundid, NULL, NULL, soundcompletecallback, NULL);
2. Play Audio
Audioservicesplaysystemsound (Soundid)//Play Sound
Audioservicesplayalertsound (Soundid)/play sound and vibrate
}

void Soundcompletecallback (systemsoundid soundid,voidvoid * clientdata) {
NSLog (@ "Play complete ...");
}

Code Section screenshot

All right, play the sound effect basically.


Play Music
We also use the framework provided by Apple Avfoundation.framework
First, create a new project

Name the project: testavgoundation

Next, import the framework

After the import was successful the following

Project structure

Before we start writing code, we find a song to put in the project
Here we have a more classic song Kin's friend

Again, we open the project default generated VIEWCONTROLLER.M to add playback functionality inside
First, import the header file

Copy Code code as follows:

#import <AVFoundation/AVFoundation.h>

Next, create a control
Copy Code code as follows:

@property (Nonatomic,strong) avaudioplayer *audioplayer;//player
@property (Strong, nonatomic) Uiprogressview *playprogress;//playback Progress
@property (Strong, nonatomic) UIButton *playorpause; Play/pause button (if tag is 0 considered to be paused, 1 is playback state)

@property (Strong, nonatomic) Nstimer *timer;//Progress Update timer

Initialize interface
Copy Code code as follows:

-(void) Viewdidload {
[Super Viewdidload];
Do no additional setup after loading the view, typically from a nib.
Self.view.backgroundcolor=[uicolor Lightgraycolor];
[Self inituserface];

}

-(void) inituserface{

Add playprogress

_playprogress= [[Uiprogressview alloc] initwithprogressviewstyle:uiprogressviewstyledefault];

_playprogress.frame=cgrectmake (0, Self.view.bounds.size.width, 36);

[Self.view addsubview:_playprogress];

Add Play button
_playorpause=[[uibutton alloc]initwithframe:cgrectmake (0, 150, 120, 36)];
[_playorpause settitle:@ "Play" forstate:uicontrolstatenormal];
[_playorpause Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];
[_playorpause addtarget:self Action: @selector (playorpauseact:) forcontrolevents:uicontroleventtouchupinside];
[Self.view Addsubview:_playorpause];

}

Add a few playback, pause, modify the song progress bar display method
Copy Code code as follows:

-(Nstimer *) timer{
if (!_timer) {
_timer=[nstimer scheduledtimerwithtimeinterval:0.5 target:self selector: @selector (updateprogress) Userinfo:nil Repeats:true];
}
return _timer;
}

-(Avaudioplayer *) audioplayer{
if (!_audioplayer) {
NSString *urlstr=[[nsbundle mainbundle]pathforresource:@ "friends. mp3" Oftype:nil];
Nsurl *url=[nsurl FILEURLWITHPATH:URLSTR];
Nserror *error=nil;
Initialize the player, note that the URL parameter here can only be a file path, does not support the HTTP URL
_audioplayer=[[avaudioplayer Alloc]initwithcontentsofurl:url error:&error];
Set player Properties
_audioplayer.numberofloops=0;//set to 0 not loop
_audioplayer.delegate=self;
[_audioplayer preparetoplay];//load audio files to cache
if (Error) {
NSLog (@ "Initialization of player process error, error message:%@", error.localizeddescription);
return nil;
}
}
return _audioplayer;
}


/**
* Play Audio
*/
-(void) play{
if (![ Self.audioplayer IsPlaying]) {
[Self.audioplayer play];
Self.timer.firedate=[nsdate distantpast];//Recovery Timer
}
}

/**
* Pause Playback
*/
-(void) pause{
if ([Self.audioplayer isplaying]) {
[Self.audioplayer pause];
Self.timer.firedate=[nsdate distantfuture];//Pause Timer, note that the Invalidate method cannot be invoked, this method is canceled, and cannot be recovered

}
}

/**
* Update Playback Progress
*/
-(void) updateprogress{
float progress= self.audioplayer.currenttime/self.audioplayer.duration;
[Self.playprogress setprogress:progress animated:true];
}

#pragma mark-Player agent method
-(void) audioplayerdidfinishplaying: (Avaudioplayer *) player successfully: (BOOL) flag{
NSLog (@ "Music playback complete ...");

[_playorpause settitle:@ "Play" forstate:uicontrolstatenormal];

}

We add click events to the play button
Copy Code code as follows:

-(void) Playorpauseact: (UIButton *) sender{
NSString *strplay=sender.titlelabel.text;
NSLog (@ "strplay=%@", Strplay);
if ([Strplay isequaltostring:@ "Play"]) {
[Sender settitle:@ "suspend" forstate:uicontrolstatenormal];
[Self play];
}else{
[Sender settitle:@ "Play" forstate:uicontrolstatenormal];
[Self pause];
}
}

Okay, so here we are, we're done, we can try.

A careful friend may find that our app plays music, and if we switch to backstage, we find that the music is paused and turned on again.
If you want to play music backstage, we need to change two places.
1, open the project plist file

Add an item

2, open VIEWCONTROLLER.M Find the following method to add a section

Okay, let's try the backstage run.

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.