Simple audio player for IOS development

Source: Internet
Author: User

Simple audio player for IOS development
The first time I got in touch with the UI part of IOS development today, I was simulating the Target-Action callback mode when I was learning OC. Today it is actually used. To familiarize yourself with the usage of basic controls and UI callback, we have developed a simple audio player to reward you with the UI learning results of this day. When using the UI control, if you have a good understanding of the Target-Action callback mode of the blog in the OC, you will feel that the usage of the control is quite satisfactory. The following simple player does not use many advanced technologies, but is just the use of some basic controls and views. Let's talk a little bit about today's audio players. In the player, we use UIProgressView (progress bar) to display the audio playback progress, and use UILabel to display the current time and total time of playing. Use UIImageView and UIImagel to add images, use UISegmentedControl to control the playback and pause, and use the UISlider to control the audio volume. The above execution components are all components in UIKit. We need to regularly obtain the audio playback time, and we also need to use NSTimer to regularly obtain the CurrentTime. How can a player reduce the key components? We also need to introduce the framework AVFoundation. framework. We will use the AVAudioPlayer component to play our audio. The following is a simple audio player: 1. Function Description: Click to play the default song, And the playback progress and current playback time are displayed. The following slider can adjust the audio size. 2. Main Development Process 1. Create a SingleView iPhone project in XCode. In order to better understand and configure controls and views, do not use storyboard to drag and drop controls. In our new project, the ViewController. m write our code. In order to hide the control and control callback methods used by our audio player, we are in ViewController. m uses extension to declare our components and methods. The Code is as follows: # import "ViewController. h "@ interface ViewController () // Add background ImageView @ property (strong, nonatomic) UIImageView * backView; // play progress bar @ property (strong, nonatomic) UIProgressView * progress; // click the tab button and assign a value to play and pause @ property (strong, nonatomic) UISegmentedControl * segment; // slider, which is used to set the volume size @ property (strong, nonatomic) UISlider * slider; // timer to update the current time of the Song @ property (strong, nonatomic) NSTimer * timer; // Lable @ property (strong, nonatomic) UILabel * label of the display time; // Add the image, and the image in the middle @ property (strong, nonatomic) UIImageView * imageView; // declare the player to play our audio file @ property (strong, nonatomic) AVAudioPlayer * player; // call back this button when paused and played-(void) tapSegment; // update the song time-(void) time; // change the sound size-(void) changeVo; @ end 2. the above is our extension part to declare the declarations and methods of our components. The specific implementation is written in @ implementation in this document, the component implementation and configuration are written in the-(void) viewDidLoad; method. This method is executed after the master view is loaded. Before writing the implementation code, we need to drag the media files we use into our Project. below is the implementation of the specific code. 1. the following code adds a background image for our application, that is, the black background image in the image above. When initializing the ImageView, we know the position and size of the view CGRectMack (x, y, width, height); use an Image to load the Image file name, insert the Image View to the bottom of the main view, and set its index. The Code is as follows. /* Add a background image * // initialize the ImageView and set the self size. backView = [[UIImageView alloc] initWithFrame: CGRectMake (0, 20,320,480)]; // load the image. Our image name is backgroundUIImage * backImage = [UIImage imageNamed: @ "background"]; // Add the background image to ImageViewself. backView. image = backImage; // Add the ImageView to the bottom layer of the view [self. view insertSubview: self. backView atIndex: 0]; 2. initialize the progress bar and set the position and size of the progress bar. The initialization value is zero. At the same time, add the progress bar to our main view through addSubView/* instantiate the progress bar and add it to the main view */self. progress = [[UIProgressView alloc] initWithFrame: CGRectMake (30, 60,240, 10)]; [self. view addSubview: self. progress]; self. progress. progress = 0; 3. adding an intermediate image is similar to adding a background image. The following code is not described here: // Add an intermediate image 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 buttons and values in each key through convenient initialization methods. During the configuration, we can use tintColor to set the color of our segment, use Target-Action to register the method for callback of the segment, and specify the callback event. When we set UIControlEventValueChange, the method we registered is called when the selectedSegmentIndex of the segment changes. The Code is as follows: // Add segmentControlself. segment = [[UISegmentedControl alloc] initWithItems: @ [@ "Play", @ "Pause"]; self. segment. frame = CGRectMake (110,255,100, 40); self. segment. tintColor = [UIColor whiteColor]; // registers the callback method. When the segment value changes, the callback registration method [self. segment addTarget: self action: @ selector (tapSegment) forControlEvents: UIControlEventValueChanged]; [self. view addSubview: self. segment]; 5. the following code initializes and configures our audio player component. Specify the url of the audio path and write back the error code: // configure the player NSBundle * bundle = [NSBundle mainBundle]; NSString * path = [bundle pathForResource: @ "music" ofType: @ "mp3"]; NSURL * musicURL = [NSURL fileURLWithPath: path]; NSError * error; self. player = [[AVAudioPlayer alloc] initWithContentsOfURL: musicURL error: & error]; if (self. player = nil) {NSLog (@ "error = % @", [error localizedDescription]);} 6. set the timer and register the method we want to call at intervals. The following timer repeatedly calls the time method in our current view in one second. In the time method, we will get the current playing time of the Current audio and display it in lable, // set the time to call the bound method self every second. timer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self selector: @ selector (time) userInfo: nil repeats: YES]; 7. add our volume control component and bind it to the method called when the slider value changes. Specify the maximum and minimum values of a slider. The Code is as follows: // Add a sliderself. slider = [[UISlider alloc] initWithFrame: CGRectMake (100,300,120, 50)]; [self. slider addTarget: self action: @ selector (changeVo) forControlEvents: UIControlEventValueChanged]; [self. view addSubview: self. slider]; // set the minimum and maximum values of the slider self. slider. minimumValue = 1; self. slider. maximumValue = 10; 3. after the component initialization and configuration are complete, we need to implement the callback method for each control. 1. when the slider value changes, we need to call the following method, that is, to set the audio of the audio player, the Code is as follows: 12345 // change the sound-(void) changeVo {self. player. volume = self. slider. value;} 2. the timer call method is as follows. In this method, we need to obtain the total audio time and the current playback time, and convert the second to minute (the following code does not use NSDateFormat to convert the time, you can use your own method to convert). After the conversion, the current time and total time are displayed in the label. The Code is as follows // Update Time-(void) time {// total time for obtaining audio NSTimeInterval totalTimer = self. player. duration; // obtain the current audio time NSTimeInterval currentTime = self. player. currentTime; // set the progress bar self based on the time ratio. progress. progress = (currentTime/totalTimer); // converts seconds to minutes NSTimeInterval currentM = currentTime/60; currentTime = (int) currentTime % 60; NSTimeInterval totalM = totalTimer/60; totalTimer = (int) totalTimer % 60; // display the time on the 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 the method of the segment callback. You can set the player playback or stop based on the selectedSegmentIndex of the segment. The Code is as follows: // method called back by the segment-(void) tapSegment {int isOn = self. segment. selectedSegmentIndex; if (isOn = 0) {[self. player play];} else {[self. player pause] ;}}

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.