iOS开发笔记--iphone开发震动与播放声音Demo

可能在软件某些时候需要震动手机以示提醒,可能还要播放一段特殊的声音引起用户的注意,在ios中如何实现呢?
首先实现震动,其实就是调用系统的方法,一句话就行,AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);当然前提是要加入AVFoundation.framework这个框架
然后实现播放声音,可能还要循环播放多少次,循环播放用n次,[self.player setNumberOfLoops:n];
因为我播放的声音是mp3,是用AudioToolbox框架,需要加入这个框架
代码如下

//ViewController.h文件
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@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

转自:http://blog.sina.com.cn/s/blog_68661bd80101d2bj.html

你可能感兴趣的:(iOS开发笔记--iphone开发震动与播放声音Demo)