//
// ViewController.h
// 音乐边播放边震动
//
// Created by ZZ_Macpro on 15/10/27.
// Copyright © 2015年 ZZ_Macpro. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
</pre><pre name="code" class="objc"><p class="p1"><span class="s1">#pragma mark-------这里只需要真机演示所以无法截图</span></p>
//
// ViewController.m
// 音乐边播放边震动
//
// Created by ZZ_Macpro on 15/10/27.
// Copyright © 2015年 ZZ_Macpro. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ViewController.h"
@interface ViewController () <AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *player;
@end
@implementation ViewController
@synthesize player;
- (void)viewDidLoad {
[super viewDidLoad];
[self prepAudio];
[self.player play];
self.player.delegate = self;
// 播放该音乐的时长
NSLog(@"%f",self.player.duration);
AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, systemAudioCallback, NULL);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
- (BOOL)prepAudio
{
NSError *error;
NSString *path = [[NSBundle mainBundle] pathForResource:@"4506" ofType:@"wav"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) return NO;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
if (!self.player)
{
NSLog(@"Error: %@", [error localizedDescription]);
return NO;
}
[self.player prepareToPlay];
[self.player setNumberOfLoops:1];
return YES;
}
void systemAudioCallback()
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
@end