Device

#import "AppDelegate.h"
#import "RootViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    RootViewController *root =[[RootViewController alloc] init];
    UINavigationController *nav =[[UINavigationController alloc] initWithRootViewController:root];
    [root release];
    self.window.rootViewController = nav
    ;
    [nav release];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

 

//  RootViewController.h
//  Device
//
//  Created by 張國鋒 on 15/7/23.
//  Copyright (c) 2015年 張國鋒. All rights reserved.
//

#import <UIKit/UIKit.h>
//帶有音頻播放器的framework
#import <AVFoundation/AVFoundation.h>

@interface RootViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate,AVAudioPlayerDelegate>

@end


//
//  RootViewController.m
//  Device
//
//  Created by 張國鋒 on 15/7/23.
//  Copyright (c) 2015年 張國鋒. All rights reserved.
//

#import "RootViewController.h"
//此framework中帶有系統預置的多媒體常量參數
#import <MobileCoreServices/MobileCoreServices.h>
#import "ImageTool.h"//對圖片進行壓縮處理的工具類
#import <MediaPlayer/MediaPlayer.h>//此framework中帶有視頻播放器
@interface RootViewController (){

    AVAudioPlayer *_audioPlayer;//音頻播放器
    //帶有視頻播放器的控制器(可以播放mp四、avi、mov格式的視頻,支持本地和遠程視頻的播放)
    MPMoviePlayerViewController*_playController;
}

@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *titles = [NSArray arrayWithObjects:@"拍照",@"相冊庫",@"音頻",@"視頻",nil];
    for (int i = 0; i<titles.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setTitle:[titles objectAtIndex:i] forState:UIControlStateNormal];
        [btn setFrame:CGRectMake(10,70+i*60,300,50)];
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 100+i;
        [self.view addSubview:btn];
    }
}

#pragma mark - customMethods
- (void)btnClicked:(UIButton *)btn{
    switch (btn.tag) {
        case 100:
        {
          //拍照功能
          //先判斷硬件是否支持拍照功能
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [self loadImagePickerWithSourceType:UIImagePickerControllerSourceTypeCamera];
            }else{
              //提示用戶
                [self showAlertViewWithMessage:@"不支持拍照功能"];
            }
        }break;
        case 101:
        {
            //調用系統相冊庫
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                [self loadImagePickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            }else {
                [self showAlertViewWithMessage:@"沒法獲取相冊庫"];
            }
        }break;
        case 102:
        {
            //音頻
            NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"song1" ofType:@"mp3"];
            //播音頻
            [self playAudioWithPath:audioPath];
            //[self haha];
            
        }break;
        case 103:
        {
            NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"];
            [self playVideoWithPath:videoPath];
            //[self hahahaha];
        }break;
        default:
            break;
    }
}

//根據不一樣的資源參數加載不一樣的資源(拍照、相冊庫)
- (void)loadImagePickerWithSourceType:(UIImagePickerControllerSourceType)type{
     //UIImagePickerController
    //經過UIImagePickerController 來獲取拍照和相冊庫資源
    UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
    //根據不一樣的參數加載不一樣的資源
    picker.sourceType = type;
    //設置代理
    picker.delegate  = self;
    //是否容許對圖片、視頻資源進行後續處理
    picker.allowsEditing = YES;
    //通常狀況下picker 習慣經過模態化的方式呈現到程序中
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

//根據不一樣的提示信息來建立警告框,用於提高用戶體驗
- (void)showAlertViewWithMessage:(NSString *)info{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"舒適提示" message:info delegate:nil cancelButtonTitle:nil otherButtonTitles:@"肯定", nil];
    //將警告框呈現到應用程序
    [alert show];
    [alert release];
}

//根據音頻的資源路徑來播放音頻
- (void)playAudioWithPath:(NSString *)audioPath{
    if (audioPath.length == 0) {
        NSLog(@"沒有音頻資源!");
        return;
    }
    //若是有舊的播放器對象,銷燬
    if (_audioPlayer) {
        [_audioPlayer release];
        _audioPlayer = nil;
    }
    //建立新的播放器對象
    //本地的資源路徑生成url用fileURLWithPath
    NSURL *url = [NSURL fileURLWithPath:audioPath];
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    //設置代理
    _audioPlayer.delegate = self;
    //對音頻資源進行預加載
    [_audioPlayer prepareToPlay];
    //播放音頻
    [_audioPlayer play];
    
    //[_audioPlayer stop];
}
//播視頻
- (void)playVideoWithPath:(NSString *)videoPath{
    if (videoPath.length == 0) {
        NSLog(@"沒有視頻資源!");
        return;
    }
    //能夠播放本地和遠程視頻
    NSURL *url;
    if ([videoPath rangeOfString:@"http://"].location !=NSNotFound || [videoPath rangeOfString:@"https://"].location!=NSNotFound) {
        url=[NSURL URLWithString:videoPath];
    }else{
        //本地資源路徑
        url = [NSURL fileURLWithPath:videoPath];
    }
    if (!_playController) {
        //建立一個帶有視頻播放器的控制器
        _playController = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
           _playController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
        //經過模態化的方式呈現
        [self presentViewController:_playController animated:YES completion:^{
            //停掉音頻播放器
            [self stopAudioPlayer];
        }];
        //視頻資源分爲普通的文件資源,還有流媒體格式(.m3u8)的視頻資源
        //moviePlayer屬性爲視頻播放器,指定播放的資源的類型
     
        //播放視頻
        [_playController.moviePlayer play];
        //經過點擊done按鈕後,銷燬_playController
        //每一個應用程序有且只有一個通知中心的對象(單例),能夠理解爲廣播站,任何對象均可以經過通知中心發送廣播
        //任何對象均可以經過通知中心註冊成爲某條廣播的觀察者(具備接收/收聽某條廣播能力的對象)
        //在通知中心註冊self爲MPMoviePlayerPlaybackDidFinishNotification廣播的觀察者,一旦有其餘對象發送這條廣播,self就能接收到並觸發playBack方法
        //addObserver 添加觀察者, selector 觸發的方法,name:廣播的名稱
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playBack) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
        //點擊done按鈕->視頻播放器會自動經過通知中心發送MPMoviePlayerPlaybackDidFinishNotification這條廣播
        //[[NSNotificationCenter defaultCenter] postNotificationName:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    }
}
- (void)playBack{
    //在通知中心移除self對MPMoviePlayerPlaybackDidFinishNotification廣播的觀察
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    if (_playController) {
        //停掉播放器
        [_playController.moviePlayer stop];
        //銷燬playController
        [_playController release];
        _playController = nil;
    }
}


//停掉音頻播放器,並銷燬
- (void)stopAudioPlayer{
    if (_audioPlayer) {
        [_audioPlayer stop];
        [_audioPlayer release];
        _audioPlayer = nil;
    }
}
#pragma mark - UIImagePickerControllerDelegate
//點擊picker上的cancel按鈕時,觸發的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"cancel!!");
    //實現picker的dismiss
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}
//點擊choose按鈕觸發的方法
//info 帶有選中資源的信息
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //判斷選中的資源的類型
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //kUTTypeImage 系統預置的圖片資源類型
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        //證實取出來的是圖片
        //經過字典獲取選中的圖片
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        //從相機中取出來的圖片佔的空間:(1M-2M)左右,須要對圖片進行壓縮處理,而後在進行後續操做
        //將原圖壓縮成50*50的尺寸
        UIImage *smallImage = [[ImageTool shareTool] resizeImageToSize:CGSizeMake(50,50) sizeOfImage:image];
        self.view.backgroundColor = [UIColor colorWithPatternImage:smallImage];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    
}

#pragma mark - AVAudioPlayerDelegate
//當成功播放完成一首歌后,調用此方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"successFully!!");
}

//當系統級別的功能介入(來電話了),播放器被打斷時,調用此方法
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
    NSLog(@"beginInterruption!");
}
//當播放器結束被打斷,調用此方法
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{
    if (player) {
        //繼續播放
        [player play];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

 

//小工具
//  ImageTool.h
//  SystemFunction
//
//  Copyright (c) 2013年 qianfeng. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ImageTool : NSObject

//返回單例的靜態方法
+(ImageTool *)shareTool;

//返回特定尺寸的UImage  ,  image參數爲原圖片,size爲要設定的圖片大小
-(UIImage*)resizeImageToSize:(CGSize)size
                 sizeOfImage:(UIImage*)image;

//在指定的視圖內進行截屏操做,返回截屏後的圖片
-(UIImage *)imageWithScreenContentsInView:(UIView *)view;

@end



//
//  ImageTool.m
//  SystemFunction
//
//  Copyright (c) 2013年 qianfeng. All rights reserved.
//

#import "ImageTool.h"
#import <QuartzCore/QuartzCore.h>

@implementation ImageTool

static ImageTool *_shareImageTool =nil;
//返回單例的靜態方法
+(ImageTool *)shareTool
{
    //確保線程安全
    @synchronized(self){
        //確保只返回一個實例
        if (_shareImageTool == nil) {
            _shareImageTool = [[ImageTool alloc] init];
        }
    }
    return _shareImageTool;
}

-(id)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

//在指定的視圖內進行截屏操做,返回截屏後的圖片
-(UIImage *)imageWithScreenContentsInView:(UIView *)view
{
    //根據屏幕大小,獲取上下文
    UIGraphicsBeginImageContext([[UIScreen mainScreen] bounds].size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return viewImage;
}


-(UIImage*)resizeImageToSize:(CGSize)size
                 sizeOfImage:(UIImage*)image
{

    UIGraphicsBeginImageContext(size);
    //獲取上下文內容
    CGContextRef ctx= UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(ctx, 0.0, size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    //重繪image
    CGContextDrawImage(ctx,CGRectMake(0.0f, 0.0f, size.width, size.height), image.CGImage);
    //根據指定的size大小獲得新的image
    UIImage* scaled= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaled;
}

@end
相關文章
相關標籤/搜索