Media Player (Avaudioplayer,mpmovieplayerviewcontroller)

Source: Internet
Author: User

Overview

This chapter mainly receives the last article about audio playback, because audio playback does not have a corresponding playback view control, so this example has drawn a simple music playback interface, including return, pause/play, progress control and so on.


results show


(Pause/Play playback progress drag back)

Process Overview

1. Take the last process to create a new music playback class, simulating the implementation of Mpmovieplayerviewcontroller;

2. When playing audio, use iOS built-in class Avaudioplayer, which supports playing music in Wav.mp3 and other formats, and its corresponding proxy class is avaudioplayerdelegate;

3. For this initialization assignment code: self._buttonplaypause = [[UIButton alloc] init]; It suddenly occurred to me that this assignment would present a memory leak . , because assigning memory directly to an attribute variable , variable retain two times and finally only Release one time. So many of the previous code is problematic . SWEAT!!!

4.nsnotificationcenter Add monitoring Note that object is not empty and should be set to nil, can not lead to difficult to find memory crash problem.


Main codeh file

musicplayerviewcontroller.h//mediaplayer////Created by God Lin on 14/12/15.//Copyright (c) 2014 Arbboter. All rights reserved.//#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @interface    Musicplayerviewcontroller:uiviewcontroller <avaudioplayerdelegate>{avaudioplayer* _audioPlayer;    uibutton* _buttonplaypause;    uibutton* _buttonreturn;    Uiimage* _imagepause;    Uiimage* _imageplay;    Uiimage* _imagereturn;    uislider* _sliderplayer;    nsurl* _urlmusic;    nstimer* _timerplayprocess;        BOOL _bplay;    uitextview* _textviewinfo; nsstring* _titlemusic;} @property (nonatomic, retain) avaudioplayer* _audioplayer; @property (nonatomic, retain) uibutton* _buttonplaypause;@ Property (Nonatomic, retain) uibutton* _buttonreturn; @property (nonatomic, retain) uislider* _sliderplayer; @property ( Nonatomic, retain) nsurl* _urlmusic, @property (nonatomic, retain) uiimage* _imagepause; @property (nonatomic, retain) uiimage* _imageplay; @properTy (nonatomic, retain) uiimage* _imagereturn; @property (nonatomic, ReadWrite) BOOL _bplay; @property (nonatomic, retain) N stimer* _timerplayprocess; @property (nonatomic, retain) uitextview* _textviewinfo; @property (nonatomic, retain) nsstring* _titlemusic;-(ID) Initwithcontenturl: (nsurl*) url;-(void) Setcontenturl: (nsurl*) URL; @endvoid                         Audiofinishedcallback (Systemsoundid idsound, void* data);

m file

musicplayerviewcontroller.m//mediaplayer////Created by God Lin on 14/12/15.//Copyright (c) 2014 Arbboter. All rights reserved.//#import "MusicPlayerViewController.h" @interface Musicplayerviewcontroller () @ End@implementation musicplayerviewcontroller@synthesize _audioplayer, _urlmusic; @synthesize _buttonPlayPause, _ Buttonreturn, @synthesize _sliderplayer, _titlemusic, @synthesize _imagepause, _imagereturn, _imageplay; @synthesize _ Bplay, _timerplayprocess, _textviewinfo;//layout-(void) Dorotateaction: (nsnotification *) notification{[self relayout];}    -(void) relayout{cgfloat x = self.view.frame.origin.x;    CGFloat y = self.view.frame.origin.y + 20;    CGFloat w = self.view.frame.size.width;        CGFloat h = self.view.frame.size.height-20;    CGFloat x1 = 0;    CGFloat y1 = 0;    CGFloat W1 = 0;    CGFloat h1 = 0;        uiimage* image = Self._imagepause;    if (W < h) {image = [UIImage imagenamed:@ "Oca.jpeg"]; } else {image = [UIImage imagenamed:@ "Flower.jpg"];        } Self.view.backgroundColor = [Uicolor colorwithpatternimage:image];    image = Self._imagereturn;    X1 = x + 5;    Y1 = y + 5;    W1 = Image.size.width;    H1 = Image.size.height;        Self._buttonreturn.frame = CGRectMake (x1, y1, W1, H1);    image = Self._imagepause;    X1 = x + 5;    Y1 = (y + h)-(image.size.height + 5);    W1 = Image.size.width;    H1 = Image.size.height;        Self._buttonplaypause.frame = CGRectMake (x1, y1, W1, H1);    X1 + = Image.size.width;    W1 = x + w-5-X1;        Self._sliderplayer.frame = CGRectMake (x1, y1, W1, H1);    X1 = x + 5;    Y1 = y + h/4;    W1 = w-10;    H1 = H/2;    nsarray* Fontarray = [Uifont familynames];    nsstring* fontname = [Fontarray objectatindex:arc4random ()%[fontarray Count]];    _textviewinfo.font = [Uifont fontwithname:fontname SIZE:H1/10];    _textviewinfo.frame = CGRectMake (x1, y1, W1, H1);    _textviewinfo.editable = NO;    _textviewinfo.textalignment = Nstextalignmentcenter; _textViewinfo.backgroundcolor = [Uicolor clearcolor];} Playback interface Controls-(void) ondragplayprocess{[Self._audioplayer setcurrenttime:self._sliderplayer.value];}        -(void) onplayprocess{self._sliderplayer.value = Self._audioplayer.currenttime;    Nsinteger ntime = _sliderplayer.value;    Nsinteger nmaxtime = _sliderplayer.maximumvalue; nsstring* info = [[NSString alloc] initwithformat:@ "%@\n%02ld:%02ld-%02ld:%02ld", _titlemusic, NTIME/60, nTime%60, NMax    TIME/60, nmaxtime%60];    _textviewinfo.text = info; [Info release];}    Set Playback file-(ID) Initwithcontenturl: (nsurl*) url{self = [super init];    if (self) {[self setcontenturl:url]; } return self;} -(void) Setcontenturl: (nsurl*) url{self._urlmusic = URL;} Start playback, before the screen appears-(void) Viewwillappear: (BOOL) animated{[self onplay];}        -(void) viewdidload{[Super Viewdidload];    Self._imageplay = [UIImage imagenamed:@ "Play.png"];    Self._imagepause = [UIImage imagenamed:@ "Pause.png"]; Self._imagereturn = [UIImage imagenamed:@"Return.png"];    It suddenly occurred to me that this assignment would be a memory leak, allocation of memory directly assigned to the attribute variable//because retain two times finally only release once, so a lot of previous problems//SWEAT!!!    uibutton* button = nil;    button = [[UIButton alloc] init];    Self._buttonplaypause = button;    [Button release];    [Self.view Addsubview:self._buttonplaypause];    [Self._buttonplaypause Setimage:self._imagepause Forstate:uicontrolstatenormal]; [Self._buttonplaypause addtarget:self Action: @selector (Onplaypause) forcontrolevents:uicontroleventtouchupinside]        ;     button = [[UIButton alloc] init];    Self._buttonreturn = button;    [Button release];    [Self.view Addsubview:self._buttonreturn];    [Self._buttonreturn Setimage:self._imagereturn Forstate:uicontrolstatenormal];        [Self._buttonreturn addtarget:self Action: @selector (OnStop) forcontrolevents:uicontroleventtouchupinside];    uislider* slider = [[UISlider alloc] init];    Self._sliderplayer = slider;    [Slider release];    [Self.view Addsubview:self._sliderplayer]; [Self._sliderplayer AddTarget: Self action: @selector (ondragplayprocess) forcontrolevents:uicontroleventvaluechanged];    uitextview* TextView = [[Uitextview alloc] init];    Self._textviewinfo = TextView;    [TextView release];        [Self.view Addsubview:_textviewinfo];        [Self relayout]; Cutting screen [[Nsnotificationcenter defaultcenter] addobserver:self selector: @sele                                               ctor (dorotateaction:) name:uideviceorientationdidchangenotification Object:self];}        -(void) onplay{if (!_bplay) {nserror* error;        Self._bplay = YES;        avaudioplayer* player = [[Avaudioplayer alloc] Initwithcontentsofurl:self._urlmusic error:&error];        Self._audioplayer = player;        [Player release];                Self._audioplayer.delegate = self; self._timerplayprocess = [Nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector (onplayprocess) UserInfo:nil Repeats:yes];        Self._audioplayer;        Self._sliderplayer.maximumvalue = 0.0f;        Set Playback duration self._sliderplayer.maximumvalue = self._audioplayer.duration;                [Self._audioplayer play];        Illegal audio if (_sliderplayer.maximumvalue = = 0) {[Self onStop];    } [self onplayprocess];    }}-(void) onstop{[self dismissviewcontrolleranimated:yes completion:nil];    [Self._audioplayer stop];    [Self._timerplayprocess invalidate]; _bplay = NO;}    -(void) onplaypause{uiimage* image = nil;    _bplay =!_bplay;        if (_bplay) {image = Self._imagepause;    [Self._audioplayer play];        } else {image = Self._imageplay;    [Self._audioplayer pause]; } [Self._buttonplaypause setimage:image forstate:uicontrolstatenormal];}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.}    -(void) dealloc{[_buttonreturn release];    [_buttonplaypause release];    [_imagereturn release];    [_imagepause release];    [_imageplay release];    [_audioplayer release];    [_urlmusic release];    [_sliderplayer release];    [[Nsnotificationcenter Defaultcenter] removeobserver:self]; [Super Dealloc];} #pragma mark-avaudioplayerdelegate-(void) audioplayerdidfinishplaying: (Avaudioplayer *) player successfully: (BOOL)    flag{NSLog (@ "Music play over"); [Self onStop];} /* If an error occurs while decoding it is reported to the delegate. */-(void) Audioplayerdecodeerrordidoccur: (Avaudioplayer *) Player ERROR: (Nserror *) error{NSLog (@ "Music Play occured ER    Ror "); [Self onStop];} @end//audio playback callback function void Audiofinishedcallback (Systemsoundid idsound, void* data) {Audioservicesdisposesystemsoundid ( Idsound);}


Project Engineering


Media Player (Avaudioplayer,mpmovieplayerviewcontroller)

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.