Play music on iPhone

Source: Internet
Author: User

Play music on iPhone



Today, we will briefly introduce how to play music on the iPhone:

We strongly recommend that you refer to the official documentation (logon required ):

Http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html%23//apple_ref/doc/uid/TP40008067



1.

Open xcode and create a new window-based application. The project name is musicplayer:







2.

Open mainwindow. XIB and add the following controls:



There are two labels at the top, the current (SEC) on the left remains unchanged, and the 0 on the right shows the current playback time. Below is a slider, similar to the progress bar of a general player, the following is the volume adjustment slider, whose min values are 0.0 and max values are 1.0. There are two buttons at the bottom.




3.

Because the avfoundation. framework is required for playing audio, we add it to our project:



Right-click frameworks, select Add/existing frameworks, and add to avfoundation:





4.

Open musicplayerappdelegate. h and modify it as follows:

////  MusicPlayerAppDelegate.h//  MusicPlayer////  Created by HuTao on 8/8/12.//  Copyright __MyCompanyName__ 2012. All rights reserved.//#import <UIKit/UIKit.h>#import <AVFoundation/AVFoundation.h>@interface MusicPlayerAppDelegate : NSObject <UIApplicationDelegate>{    UIWindow * window;    IBOutlet UIButton * btnPlay;    IBOutlet UILabel * labelVolume;    IBOutlet UILabel * labelCurrentTime;    IBOutlet UISlider * sliderCurrentTime;    NSTimer * playTimer;    AVAudioPlayer * player;}@property (nonatomic, retain) IBOutlet UIWindow * window;@property (nonatomic, retain) IBOutlet UIButton * btnPlay;@property (nonatomic, retain) IBOutlet UILabel * labelVolume;@property (nonatomic, retain) IBOutlet UILabel * labelCurrentTime;@property (nonatomic, retain) IBOutlet UISlider * sliderCurrentTime;-(IBAction)soundStartOrPause:(id)sender;-(IBAction)soundStop:(id)sender;-(IBAction)volumeChanged:(id)sender;-(IBAction)currentTimeChanged:(id)sender;-(void)updateSoundAt:(float)percent;-(void)updateCurrentTime;-(void)initPlayer;@end

First, add:

#import <AVFoundation/AVFoundation.h>

Second:

Btnlabel,Labelvolume,Labelcurrenttime,Slidercurrenttime is the outlet corresponding to the control:

Btnlabel: After the start button is clicked, the text must be changed to pause. Therefore, an outlet is added to the button;

Labelvolume and labelcurrenttime: the label corresponding to slider needs to be changed to reflect the current value;

Slidercurrenttime: when playing a song, you must use the slider to reflect the current playback time. Therefore, the slider also needs an outlet.


Playertimer runs at a certain time and updates the progress bar based on the current playback time. avaudioplayer is a class for playing music provided by avfoundation.


The following four ibactions are: press the start button, press the stop button, Slider the volume, and slide the action corresponding to the played time.




5.

Open musicplayerappdelegate. M and modify it as follows:

/// Musicplayerappdelegate. M // musicplayer //// created by FIG on 8/8/12. // copyright _ mycompanyname _ 2012. all rights reserved. // # import "musicplayerappdelegate. H "@ implementation progress @ synthesize window; @ synthesize btnplay; @ synthesize labelvolume; @ synthesize labelcurrenttime; @ synthesize slidercurrenttime; # pragma mark-# pragma mark application lifecycle) application :( uiap Plication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions {// initialize avaudioplayer [self initplayer]; [Window makekeyandvisible]; return yes;}-(void) initplayer {nsstring * Path = [[nsbundle mainbundle] pathforresource: @ "Beijing Welcomes You" oftype: @ "MP3"]; // determines whether the music file is found if (PATH) {nslog (@ "init sound"); // use the path to initialize avaudioplayer player = [[avaudioplayer alloc] initwithcontentsofurl: [nsurl Lloc] initfileurlwithpath: path] error: Nil]; // initialize the player [Player preparetoplay]; // set the number of playback cycles: if numberofloops is a negative audio file, it will be played continuously. numberofloops =-1; // set the audio volume. The value range of volume is [0.0f, 0.1f. volume = 0.5f; // set the current playback progress to 0 [self updatesoundat: 0.0f] ;}}-(void) updatesoundat :( float) percent {float attime = (player? Player. duration * percent: 0.0f); nsstring * time = [nsstring stringwithformat: @ "% d", (INT) attime]; labelcurrenttime. TEXT = time; slidercurrenttime. value = percent;}-(ibaction) soundstartorpause :( ID) sender {// click the start button to start playing the music if (player) {uibutton * BTN = (uibutton *) sender; if (! [PLAYER isplaying]) {nslog (@ "Start sound"); [player play]; [BTN settitle: @ "pause" forstate: uicontrolstatenormal]; If (! Playtimer) {playtimer = [nstimer scheduledtimerwithtimeinterval: 0.5 target: Self selector: @ selector (updatecurrenttime) userinfo: Nil repeats: Yes];} else {nslog (@ "Pause sound"); [Player pause]; [BTN settitle: @ "start" forstate: uicontrolstatenormal] ;}}-(void) updatecurrenttime {[self updatesoundat: 1.0 * player. currenttime/player. duration];}-(ibaction) soundstop :( ID) sender {// stop playing sound if (player ){ Nslog (@ "Stop sound"); player. currenttime = 0; [Player stop]; [btnplay settitle: @ "start" forstate: uicontrolstatenormal]; [self updatesoundat: 0.0f]; }}- (ibaction) volumechanged :( ID) sender {uislider * slider = (uislider *) sender; nsstring * value = [[nsstring alloc] initwithformat: @ "% d %", (INT) (slider. value * 100)]; labelvolume. TEXT = value; player. volume = slider. value; [value release];}-(ibaction) Currenttimechanged :( ID) sender {uislider * slider = (uislider *) sender; int time = (player? Slider. value * player. duration: 0); player. currenttime = time; [self updatesoundat: slider. value];}-(void) dealloc {[Window release]; [btnplay release]; [labelvolume release]; [labelcurrenttime release]; [slidercurrenttime release]; [Super dealloc];} @ end


There are several notes:

1. Add the music to resouces;

2. The playtimer timer runs once every 0.5 seconds to update the current progress bar;




6.

The following describes how to connect the control with iboutlet and ibaction:

()

Open mainwindow. XIB, press Ctrl, and drag the mouse from the music player Delegate to the corresponding label to connect it to iboutlet:


Note that do not forget to connect to btnstart! Two slider, two labels, and one button must be connected.



(B)

Right-click the button, select touch up inside, and drag the circleOn music player delegate, connect the corresponding ibaction:




Note that slider needs to connect to the valuechanged event:






7.

The running result is as follows:





Finally, I uploaded the Code:

Http://download.csdn.net/detail/htttw/4484442





Done!

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.