//后台播放音乐 -(void)playAudio{ dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(dispatchQueue, ^(void) { NSError *audioSessionError = nil; AVAudioSession *audioSession = [AVAudioSession sharedInstance]; if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){ NSLog(@"Successfully set the audio session."); } else { NSLog(@"Could not set the audio session"); } NSBundle *mainBundle = [NSBundle mainBundle]; NSString *filePath = [mainBundle pathForResource:@"mySong" ofType:@"mp3"]; NSData *fileData = [NSData dataWithContentsOfFile:filePath]; NSError *error = nil; self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error]; if (self.audioPlayer != nil){ self.audioPlayer.delegate = self; [self.audioPlayer setNumberOfLoops:-1]; if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){ NSLog(@"Successfully started playing..."); } else { NSLog(@"Failed to play."); } } }); }
调用方法一: SystemSoundID myAlertSound; NSURL *url = [NSURL URLWithString:@"/System/Library/Audio/UISounds/begin_video_record.caf"]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &myAlertSound); AudioServicesPlaySystemSound(myAlertSound); 调用方法二: NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"]; if (path) { SystemSoundID theSoundID; OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &theSoundID); if (error == kAudioServicesNoError) { AudioServicesPlaySystemSound(theSoundID); } else { NSLog(@"Failed to create sound "); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/etmanwenhan/article/details/48048247