可能在软件某些时候需要震动手机以示提醒,可能还要播放一段特殊的声音引起用户的注意,在ios中如何实现呢?
首先实现震动,其实就是调用系统的方法,一句话就行,AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);当然前提是要加入AVFoundation.framework这个框架
然后实现播放声音,可能还要循环播放多少次,循环播放用n次,[self.player setNumberOfLoops:n];
因为我播放的声音是mp3,是用AudioToolbox框架,需要加入这个框架
代码如下
ViewController.h文件
#import
#import
#import
@interface ViewController : UIViewController{
AVAudioPlayer *player;
}
@property (retain) AVAudioPlayer *player;
@end
ViewController.m文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize player;
- (BOOL) prepAudio
{
NSError *error;
NSString *path = [[NSBundle mainBundle] pathForResource:@"loop" ofType:@"mp3"];
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)viewDidLoad
{
[self prepAudio];
[self.player play];
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
}
@end
下载源代码http://www.kuaipan.cn/file/id_30491149655343777.htm
声音逐渐减小
for (int i = 9; i >= 0; i--)
{
self.player.volume = i / 10.0f;
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
}
[self.player pause];
发生中断时的处理
[[NSUserDefaults standardUserDefaults] setFloat:[self.player currentTime] forKey:@"Interruption"];
首先实现震动,其实就是调用系统的方法,一句话就行,AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);当然前提是要加入AVFoundation.framework这个框架
然后实现播放声音,可能还要循环播放多少次,循环播放用n次,[self.player setNumberOfLoops:n];
因为我播放的声音是mp3,是用AudioToolbox框架,需要加入这个框架
代码如下
ViewController.h文件
#import
#import
#import
@interface ViewController : UIViewController{
AVAudioPlayer *player;
}
@property (retain) AVAudioPlayer *player;
@end
ViewController.m文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize player;
- (BOOL) prepAudio
{
NSError *error;
NSString *path = [[NSBundle mainBundle] pathForResource:@"loop" ofType:@"mp3"];
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)viewDidLoad
{
[self prepAudio];
[self.player play];
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
}
@end
下载源代码http://www.kuaipan.cn/file/id_30491149655343777.htm
声音逐渐减小
for (int i = 9; i >= 0; i--)
{
self.player.volume = i / 10.0f;
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
}
[self.player pause];
发生中断时的处理
[[NSUserDefaults standardUserDefaults] setFloat:[self.player currentTime] forKey:@"Interruption"];