The simple audio player developed by iOS

Source: Internet
Author: User

Today, the first time I touched the UI part of iOS development, I used the target-action callback mode to simulate the use of OC, which was really used once today. To familiarize yourself with the basics of how the controls are used, and the UI part of the callback, a particularly simple audio player has been developed to reward the UI learning results of this day. When using UI controls, it is handy to feel the use of a control if you understand the target-action callback pattern in the OC before the blog. The following simple player does not use much advanced technology, just some basic controls and view usage.

Don't talk a little bit about today's audio player. In the player we use the Uiprogressview (progress bar) to display the audio playback progress, with Uilabel display the current time and the total time of the play. Use Uiimageview and Uiimagel to add images, use Uisegmentedcontrol to control playback and pauses, and use the slider uislider to control the audio volume. The above actor is the component in the Uikit, we want to get the audio playback time regularly, we also need to use Nstimer to get currenttime regularly. We also need to introduce the framework avfoundation.framework to how the player can have less critical components. We'll use the component Avaudioplayer to play our audio.

The following is a simple audio player:

?    ?    ?    ?    ? ?

? 1. Function Description:

? Click Play will play the default song, while the playback progress and play the current time, the slider below can adjust the sound size of the audio.

?

? 2. Main development process

?    ? ? 1. Create a new Singleview iphone in our Xcode project, in order to better understand and configure the control and view, do not use storyboard to drag and drop the control. In order to hide the control and control callbacks we use in our audio player, we declare our components and methods in VIEWCONTROLLER.M, using the VIEWCONTROLLER.M in our new project to write our code. The code is as follows:

1234567891011121314151617181920212223242526272829303132333435363738 #import "ViewController.h" @interface ViewController ()//添加背景用的ImageView@property (strong, nonatomic) UIImageView *backView;//播放进度条@property (strong, nonatomic) UIProgressView *progress;//选项卡按钮,赋值播放和暂停@property (strong, nonatomic) UISegmentedControl * segment;//slider,用滑动器来设置音量的大小@property (strong, nonatomic) UISlider *slider;//timer,来更新歌曲的当前时间@property (strong, nonatomic) NSTimer *timer; //显示时间的lable@property (strong, nonatomic) UILabel *label;//加入图片,中间的图片@property (strong, nonatomic) UIImageView *imageView;//声明播放器,来播放我们的音频文件@property (strong, nonatomic) AVAudioPlayer *player;//在暂停和播放时回调此按钮-(void)tapSegment;//更新歌曲时间-(void)time;//改变声音大小-(void) changeVo;@end

? 2. Above is our extension section, to carry out the declaration of our components and the declaration of methods, the specific implementation is written in this document @implementation, we put the implementation and configuration of components in-(void) viewdidload; This method executes after the main view has finished loading. Before we write the implementation code, we'll drag the media files we use into our project, and here's the implementation of the specific code.

?    ? ? 1. The following code is to add a background image for our application, which is the black background image in our image above, we know the position and size of the view when initializing ImageView cgrectmack (x, y, width, height); Use image to load our picture with the name of the picture file, insert the picture view into the bottom of the main viewing, and set its index to implement, the code is as follows.

123456789 /*添加背景图片*///初始化ImageView,并设置大小self.backView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, 320, 480)];//加载图片,我们的图片名为backgroundUIImage *backImage = [UIImage imageNamed:@"background"];//添加背景图片到ImageViewself.backView.image = backImage;//把ImageView添加到view的最底层[self.view insertSubview:self.backView atIndex:0];

?    ? ? 2. Initialize our progress bar and set the position and size of the progress bar, and initialize the progress value to zero. and add the progress bar to our main view via Addsubview.

1234 /*实例化进度条,并添加到主视图*/self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 60, 240, 10)];[self.view addSubview:self.progress];self.progress.progress = 0;

?    ? 3. Add the middle of the picture, and add a background image similar, in this will not repeat the code as follows:

12345 //添加中间的图片  self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 90, 160, 150)];  UIImage *image = [UIImage imageNamed:@"image.png"];  self.imageView.image = image;  [self.view addSubview:self.imageView];

?    ? ?

    ?    ?    ?4. Initialize our segment, while initializing the segment, We can specify several keys and values in each key by facilitating the initialization method. When configured, we can set the color of our segment through Tintcolor, register the method of segment to callback by Target-action, and specify the callback event, we set the time Uicontroleventvaluechange, is when segment's selectedsegmentindex changes, call our method of registration. The code is as follows:       ?

1234567 //添加segmentControlself.segment = [[UISegmentedControl alloc] initWithItems:@[@"Play", @"Pause"]];self.segment.frame = CGRectMake(110, 255, 100, 40);self.segment.tintColor = [UIColor whiteColor];//注册回调方法,在segment的值改变的时候回调注册的方法[self.segment addTarget:self action:@selector(tapSegment) forControlEvents:UIControlEventValueChanged];[self.view addSubview:self.segment];

    ?    ?    ?5. The following code is to initialize and configure our audio player components, configuration specifies the URL of the path where our audio is located, and the error code for writeback playback is as follows

123456789 //Configure player nsbundle *bundle = [NSBundle mainbundle]; nsstring * path = [bundle pathforresource:@  oftype:@ ; nsurl *musicurl = [Nsurl Fileurlwithpath:path]; nserror *error; self.player = [[Avaudioplayer alloc] Initwithcontentsofurl:musicurl error:&error]; if   (Self.player = nil) {      nslog (@

?    ? ? 6. Set the timer and register the method we want to call at intervals. The following timer is a 1-second call to the time method in our current view, in which we will get the current playback times of the current audio and display it in lable, which will be mentioned later.

12 //设置时间,每一秒钟调用一次绑定的方法self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(time) userInfo:nil repeats:YES];

?    ? ?

?    ? ? 7. Add our Volume control component and bind when the slider's value change is called which method. Specify both the maximum and minimum values for the slider, and the code is as follows:

12345678 //添加sliderself.slider = [[UISlider alloc] initWithFrame:CGRectMake(100,300, 120 , 50)];[self.slider addTarget:self action:@selector(changeVo) forControlEvents:UIControlEventValueChanged];[self.view addSubview:self.slider];//设置slider最小值和最大值self.slider.minimumValue = 1;self.slider.maximumValue = 10;

? ? 3. When the components are initialized and configured, we have to implement the methods for each control to callback.

?    ? ? 1. When the value of the slider is changed we want to call the method below, is to set the audio player's sound, the code is as follows:

12345 //改变声音-(void)changeVo{    self.player.volume = self.slider.value;}

?    ? ?

?    ? ? 2. Timer Call method is as follows, in this method we want to get the total audio time and the current playback time, and the seconds to convert the component clock (the following code does not use Nsdateformat to convert the time, the reader can use their own method to convert), Display the current time and total time in the label after the conversion, the code is as follows

123456789101112131415161718192021 //更新时间-(voidtime{    //获取音频的总时间    NSTimeInterval totalTimer = self.player.duration;    //获取音频的当前时间    NSTimeInterval currentTime = self.player.currentTime;    //根据时间比设置进度条的进度    self.progress.progress = (currentTime/totalTimer);        //把秒转换成分钟    int currentM = currentTime/60;    currentTime = (int)currentTime%60;        int totalM = totalTimer/60;    totalTimer = (int)totalTimer%60;        //把时间显示在lable上    NSString *timeString = [NSString stringWithFormat:@"%02.0f:%02.0f|%02.0f:%02.0f",currentM, currentTime, totalM,totalTimer];    self.label.text = timeString;}

?    ? ? 3. The following is a segment to callback method to set the player's playback or stop according to segment Selectedsegmentindex, the code is as follows:

123456789101112131415 //segment所回调的方法-(void) tapSegment{    intisOn = self.segment.selectedSegmentIndex;    if(isOn == 0)    {        [self.player play];            }    else    {        [self.player pause];    } }

?

?    ? The above is the entire simple player code, the function is particularly simple, so the code is not much. Mainly through the above simple player to familiarize with the iOS development control and view of the use of the process, I have been learning, the level is limited, welcome criticism.

The simple audio player developed by iOS

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.