iOS播放音乐文件时的操作和打断处理

来源:互联网 发布:百度指数 数据导出 编辑:程序博客网 时间:2024/06/05 18:16
//播放音乐文件打断处理void interruptionListenner(void* inClientData, UInt32 inInterruptionState){    AppDelegate* pTHIS = (__bridge AppDelegate*)inClientData;    //AppDelegate *applegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];    if (pTHIS) {        NSLog(@"interruptionListenner %d", inInterruptionState);        if (kAudioSessionBeginInterruption == inInterruptionState) {            NSLog(@"Begin interruption");//开始打断打断处理            [pTHIS.self.player pause];        }        else if (inInterruptionState == kAudioSessionEndInterruption)        {            NSLog(@"End end interruption");//结束打断处理            [pTHIS.self.player resume];        }    }}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    // Override point for customization after application launch.    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    //[defaults setObject:nil forKey:@"KKUserToken"];    [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayback error:nil];    //向DocumentDir下创建文件夹    NSString *cacheDir = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];    NSString *cacheFolder = [cacheDir stringByAppendingPathComponent:@"musicTest"];    // ensure all cache directories are there (needed only once)    NSError *error = nil;    if(![[NSFileManager new] createDirectoryAtPath:cacheFolder withIntermediateDirectories:YES attributes:nil error:&error]) {#ifdef DDLogError        DDLogError(@"[NCMusicEngine] Failed to create cache directory at %@", cacheFolder);#else        NSLog(@"[NCMusicEngine] Failed to create cache directory at %@", cacheFolder);#endif    }    self.bgImageView = [[UIImageView alloc] init];    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];    [[AVAudioSession sharedInstance] setActive: YES error: nil];    //实时监测网络状态..    //开启网络状况的监听    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(reachabilityChanged:)                                                 name: kReachabilityChangedNotification                                               object: nil];    hostReach = [Reachability reachabilityWithHostname:@"www.baidu.com"];//可以以多种形式初始化    [hostReach startNotifier];  //开始监听,会启动一个run loop    [self updateInterfaceWithReachability:hostReach];    AudioSessionInitialize(NULL, NULL, interruptionListenner, (__bridge void*)self);    NSError *setCategoryErr = nil;    NSError *activationErr  = nil;    [[AVAudioSession sharedInstance]     setCategory: AVAudioSessionCategoryPlayback     error: &setCategoryErr];    [[AVAudioSession sharedInstance]     setActive: YES     error: &activationErr];    //隐藏系统的tabbar按钮    UITabBarController *tabBarCon = (UITabBarController *)self.window.rootViewController;    tabBarCon.tabBar.hidden = YES;    //添加定制的tabbar控键    self.tabBarController = [[AKTabBarController alloc] initWithTabBarHeight:(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 70 : 50];    [self.tabBarController setMinimumHeightToDisplayTitle:40.0];    UIViewController *settingController = [[SettingViewController alloc] init];    UINavigationController *navSetting = [[UINavigationController alloc] initWithRootViewController:settingController];    UIViewController *findController = [[FindViewController alloc] init];    UINavigationController *navFinding = [[UINavigationController alloc] initWithRootViewController:findController];    UIViewController *musicController = [[MusicViewController alloc] init];    UINavigationController *navMusicing = [[UINavigationController alloc] initWithRootViewController:musicController];    [self.tabBarController setViewControllers:[NSMutableArray arrayWithObjects:                                           navFinding,                                           navMusicing,                                           navSetting, nil]];//    UINavigationController *musicNavigation = [[UINavigationController alloc] initWithRootViewController:_tabBarController];    self.welcomeView = [[WelcomeControllerViewController alloc] initWithNibName:@"WelcomeControllerViewController" bundle:nil];    self.loginView = [[LogInViewController alloc] initWithNibName:@"LogInViewController" bundle:nil];    [_window setRootViewController:self.welcomeView];    [_window makeKeyAndVisible];    // initial music engine    /////////////////////////////////////////////////////////////////////    self.player = [[NCMusicEngine alloc] init];    self.player.delegate = nil;    self.playList = [[NSMutableArray alloc]initWithCapacity:0];    dbDatabase = [[FMDBNotes alloc] init];    //播放当前歌曲的列表个数第几个    [[NSUserDefaults standardUserDefaults] setInteger:101 forKey:@"playCellCount"];    return YES;}- (void)applicationWillResignActive:(UIApplication *)application{    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application{    NSLog(@"进入后台需要处理的事情..");    [self readingCaches];    UIApplication*   app = [UIApplication sharedApplication];    __block    UIBackgroundTaskIdentifier bgTask;    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{        dispatch_async(dispatch_get_main_queue(), ^{            if (bgTask != UIBackgroundTaskInvalid)            {                bgTask = UIBackgroundTaskInvalid;            }        });    }];    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        dispatch_async(dispatch_get_main_queue(), ^{            if (bgTask != UIBackgroundTaskInvalid)            {                bgTask = UIBackgroundTaskInvalid;            }        });    });    //进入后台需要处理的锁屏界面的切换歌曲///    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];    [self becomeFirstResponder];    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application{    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.    //[self.playView updateUIData];    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];    [self resignFirstResponder];}-(void)remoteControlReceivedWithEvent:(UIEvent *)event{    //if it is a remote control event handle it correctly    if (event.type == UIEventTypeRemoteControl) {        switch (event.subtype) {            case UIEventSubtypeRemoteControlPause:                if( self.player.playState==NCMusicEnginePlayStatePlaying ) {                    [self.player pause];                    [self.playView.btnPlay setImage:[UIImage imageNamed:@"play_icon_100px.png"] forState:UIControlStateNormal];                }                //[self.audioPlayer pause];                break;            case UIEventSubtypeRemoteControlPlay:                if (self.player.playState==NCMusicEnginePlayStatePaused || self.player.playState==NCMusicEnginePlayStateStopped) {                    [self.player resume];                    [self.playView.btnPlay setImage:[UIImage imageNamed:@"pause_icon_100px.png"] forState:UIControlStateNormal];                }                break;            case UIEventSubtypeRemoteControlPreviousTrack:                [self previousPlayMusicInFo];                    break;            case UIEventSubtypeRemoteControlNextTrack:                [self nextPlayMusicInFo];                    break;            default:                break;        }    }}//Make sure we can recieve remote control events- (BOOL)canBecomeFirstResponder {    return YES;}- (void)applicationDidBecomeActive:(UIApplication *)application{    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}//获取缓存文件路径-(NSString *)getCachesPath{    // 获取Caches目录路径    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *cachesDir = [paths objectAtIndex:0];    NSString *filePath = [cachesDir stringByAppendingPathComponent:@"com.nickcheng.NCMusicEngine"];    return filePath;}-(void)readingCaches{    // 获取Caches目录路径    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *cachesDir = [paths objectAtIndex:0];    //读取缓存里面的具体单个文件/或全部文件//    NSString *filePath = [cachesDir stringByAppendingPathComponent:@"com.nickcheng.NCMusicEngine"];    NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];    NSFileManager* fm=[NSFileManager defaultManager];    if([fm fileExistsAtPath:filePath]){        //取得一个目录下得所有文件名        NSString *exe = [filePath lastPathComponent];        NSLog(@"exeexe ====%@",exe);    }}- (void)applicationWillTerminate:(UIApplication *)application{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.    NSUserDefaults *userdefaultsWifi = [NSUserDefaults standardUserDefaults];    [userdefaultsWifi setBool:YES forKey:@"OneEnter"];    [[NSUserDefaults standardUserDefaults] setInteger:101 forKey:@"playCell"];    ////////    //设置没有缓存完成的歌曲从Document下缓存文件删除.....    //[self readingCaches];}// 连接改变- (void) reachabilityChanged: (NSNotification* )note{    NSLog(@"连接开始改变了。。。。");    Reachability* curReach = [note object];    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);    [self updateInterfaceWithReachability: curReach];}//处理连接改变后的情况- (void) updateInterfaceWithReachability: (Reachability*) curReach{NSLog(@"连接改变后处理一下改变后情况");    //对连接改变做出响应的处理动作。    NetworkStatus status = [curReach currentReachabilityStatus];    if (status == NotReachable) {  //没有连接到网络就弹出提实况        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My App Name"                                                        message:@"没有网络连接,请检查网络!"                                                        delegate:nil                                                        cancelButtonTitle:@"YES" otherButtonTitles:nil];        //[alert show];    }else if (status == ReachableViaWiFi){        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My App Name"                                                        message:@"以连接无线网络!"                                                        delegate:nil                                                    cancelButtonTitle:@"YES" otherButtonTitles:nil];        //[alert show];    }else if (status == ReachableViaWWAN){        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My App Name"                                                    message:@"以使用手机流量2G/3G/4G!"                                                    delegate:nil                                                cancelButtonTitle:@"YES" otherButtonTitles:nil];        //[alert show];    }}
0 0
原创粉丝点击