iOS Development-Music playback (Avaudioplayer)

Source: Internet
Author: User

Now the cell phone basically no one is constantly music, we can not imagine in a world without sound how we will be, the mainstream of the mainstream NetEase cloud music, QQ music, cool dog, shrimp, every day basically occupy all the user groups, but did not hinder everyone's pursuit of music, Le Stream is a breakout success, reportedly sold to QQ, interested can see. We can not do so tall on the first to do a simple, the core is playing, pausing, cutting songs, and other basically around this tinkering icing on the cake, such as song name, album, who listened to this song ... Cushion more, directly see the effect bar, three buttons a progress bar:

Initialize button:

 Self.playbutton=[[uibutton Alloc]initwithframe:cgrectmake (40, 100, 60, 30)];    [Self.playbutton settitle:@ "Play" forstate:uicontrolstatenormal];    [Self.playbutton Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];    [Self.playButton.titleLabel Setfont:[uifont systemfontofsize:14]; Self.playbutton.layer.bordercolor=[uicolor Blackcolor].    Cgcolor;    self.playbutton.layer.borderwidth=1.0;    self.playbutton.layer.cornerradius=5.0;    [Self.playbutton addtarget:self Action: @selector (Playmusic:) forcontrolevents:uicontroleventtouchupinside];                [Self.view AddSubview:self.playButton];    Self.pausebutton=[[uibutton Alloc]initwithframe:cgrectmake (140, 100, 60, 30)];    [Self.pausebutton settitle:@ "pause" forstate:uicontrolstatenormal];    [Self.pausebutton Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];    [Self.pauseButton.titleLabel Setfont:[uifont systemfontofsize:14]; Self.pausebutton.layer.bordercolor=[uicolor Blackcolor].    Cgcolor;self.pausebutton.layer.borderwidth=1.0;    self.pausebutton.layer.cornerradius=5.0;    [Self.pausebutton addtarget:self Action: @selector (Pausemusic:) forcontrolevents:uicontroleventtouchupinside];            [Self.view AddSubview:self.pauseButton];    Self.switchbutton=[[uibutton Alloc]initwithframe:cgrectmake (240, 100, 60, 30)];    [Self.switchbutton settitle:@ "cut song" Forstate:uicontrolstatenormal];    [Self.switchbutton Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];    [Self.switchButton.titleLabel Setfont:[uifont systemfontofsize:14]; Self.switchbutton.layer.bordercolor=[uicolor Blackcolor].    Cgcolor;    self.switchbutton.layer.borderwidth=1.0;    self.switchbutton.layer.cornerradius=5.0;    [Self.switchbutton addtarget:self Action: @selector (Switchmusic:) forcontrolevents:uicontroleventtouchupinside]; [Self.view AddSubview:self.switchButton];

Initialize the progress bar:

  Self.progressview=[[uiprogressview Alloc]initwithframe:cgrectmake (+, +, +)];    [Self.view AddSubview:self.progressView];

Avaudioplayer can be seen as a simple player, support a variety of audio formats, the ability to progress, volume, playback speed control, has met the basic needs, followed by the music playing code:

   if (self.audioPlayer.isPlaying) {        [self.audioplayer pause];    } else{        [self loadmusicbyasset:[[avurlasset alloc] initwithurl:[[nsbundle Mainbundle] urlforresource:@ "My Dearest" withextension:@ "MP3"] options:nil];        [Self.audioplayer play];    }

instantiation of Avaudioplayer :

-(void) Loadmusicbyasset: (avurlasset*) Avurlasset {        if ([[Nsfilemanager Defaultmanager] Fileexistsatpath: AvUrlAsset.URL.path]) {        nserror *error=nil;        self.audioplayer= [[Avaudioplayer alloc] InitWithContentsOfURL:avUrlAsset.URL error:&error];        self.audioplayer.delegate=self;        Prepare buffer to reduce the time of playback delay        [Self.audioplayer preparetoplay];        [Self.audioplayer setvolume:1]; Set the volume size        self.audioPlayer.numberOfLoops =0;//set play times, 0 for play once, negative for loop play        if (error) {            NSLog (@ "Initialization error:%@", error.localizeddescription);}}}    

The above is instantiated by Avurlasset, and can be instantiated directly by name:

-(void) Loadmusic: (nsstring*) name {    NSString *musicfilepath = [[NSBundle mainbundle] Pathforresource:name ofType:@ "MP3"]; Create a music file path        if ([[[Nsfilemanager Defaultmanager] Fileexistsatpath:musicfilepath]) {        Nsurl *musicurl = [[Nsurl] Alloc] Initfileurlwithpath:musicfilepath];        Nserror *error=nil;        self.audioplayer= [[Avaudioplayer alloc] Initwithcontentsofurl:musicurl error:&error];        self.audioplayer.delegate=self;        Prepare buffer to reduce the time of playback delay        [Self.audioplayer preparetoplay];        [Self.audioplayer setvolume:1]; Set the volume size        self.audioPlayer.numberOfLoops =0;//set play times, 0 for play once, negative for loop play        if (error) {            NSLog (@ "Initialization error:%@", error.localizeddescription);}}}    

Pause music, here in order to facilitate the individual write a button, in most cases, the playback is the same button is paused, for reference only:

-(void) Pausemusic: (UIButton *) sender{    if (self.audioPlayer.isPlaying) {        [self.audioplayer pause];    }}

Cut a song is usually the last one Duflot, very good understanding:

-(void) Switchmusic: (UIButton *) sender{    [Self.audioplayer stop];    [Self Loadmusicbyasset:[[avurlasset alloc] initwithurl:[[nsbundle Mainbundle] urlforresource:@ "I Need a Dollar" withExtension : @ "MP3"] options:nil];    [Self.audioplayer play];}

Update the progress bar in real time with the timer:

  Self.timer = [Nstimer scheduledtimerwithtimeinterval:0.1 target:self                                                selector: @selector (changeprogress)                                                Userinfo:nil Repeats:yes];

 Progress Update:

-(void) changeprogress{    if (self.audioPlayer.isPlaying) {        self.progressView.progress = self.audioplayer.currenttime/self.audioplayer.duration;}    }

The effect is as follows:

after the music playback is complete, you can Avaudioplayerdelegate's The proxy method executes its own arrangement according to the business scenario:

-(void) audioplayerdidfinishplaying: (Avaudioplayer *) player successfully: (BOOL) flag{//     [Self.timer invalidate] , directly destroyed, then unavailable, carefully considered    //    [Self.timer setfiredate:[nsdate Date]];//Continue//    [Self.timer setfiredate:[nsdate distantpast]];//Open    [Self.timer setfiredate:[nsdate distantfuture]];//Pause}

basically the most commonly used is so many, weekend discovery Fast ~

iOS Development-Music playback (Avaudioplayer)

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.