首页 > 代码库 > 摇一摇

摇一摇

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #c91b13 } span.s1 { color: #822e0e } span.s2 { }</style>

#import <AudioToolbox/AudioToolbox.h>

 

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #3d1d81 } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #1d9421 } p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; min-height: 21.0px } p.p5 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px "PingFang SC"; color: #1d9421 } span.s1 { } span.s2 { color: #c32275 } span.s3 { color: #000000 } span.s4 { font: 18.0px "PingFang SC" } span.s5 { font: 18.0px Menlo; color: #000000 } span.s6 { font: 18.0px Menlo } span.s7 { color: #703daa } span.s8 { color: #6122ae } span.s9 { color: #c91b13 } span.s10 { color: #3d1d81 } span.s11 { font: 18.0px "PingFang SC"; color: #c91b13 }</style>

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    // iOS,音频包括短效音频和音乐, 短效音频的实现用的是系统的AudioToolBox, 音乐播放使用的是AVFoundation框架

    // 短效音频: 播放过程不可控, 长度不超过30

    

    // 定义一个系统声音id

    SystemSoundID soundId;

    

    // 设置播放短效音频的资源

    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)([[NSBundle mainBundle] URLForResource:@"shake" withExtension:@"wav"]), &soundId);

    

    // 设置震动的效果, 需要真机

//    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

    

     // 播放短效音频

    AudioServicesPlaySystemSound(soundId);

 

 

//很简单,你只需要让这个Controller本身支持摇动
 
//同时让他成为第一相应者:
    [[UIApplicationsharedApplication] setApplicationSupportsShakeToEdit:YES];
 
    [selfbecomeFirstResponder];

    

}

 

// 摇一摇 依赖于重力感应原理

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {

    

    // 定义一个系统声音id

    SystemSoundID soundId;

    

    // 设置播放短效音频的资源

    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)([[NSBundle mainBundle] URLForResource:@"shake" withExtension:@"wav"]), &soundId);

    

    // 设置震动的效果, 需要真机

    //    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

    

    // 播放短效音频

    AudioServicesPlaySystemSound(soundId);

    

    NSLog(@"摇动开始");

}

 

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {

    

    NSLog(@"摇动结束");

}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {

    

    NSLog(@"摇动取消");

}

摇一摇