一 · 首先在capabilities 勾选
二 ·设置 AVAudioSession AVAudioSessionCategoryPlayback
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
void EMSystemSoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data)
{
AudioServicesDisposeSystemSoundID(sound_id);
}
-(void)run
{
[self playVibration];
[self playNewMessageSound];
//后台播放声音
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
}
// 播放接收到新消息时的声音
- (SystemSoundID)playNewMessageSound
{
// 要播放的音频文件地址
// NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"EaseUIResource" withExtension:@"bundle"];
// NSURL *audioPath = [[NSBundle bundleWithURL:bundlePath] URLForResource:@"in" withExtension:@"caf"];
NSString *str = [[NSBundle mainBundle]pathForResource:@"in.caf" ofType:nil];
NSURL* audioPath =[NSURL URLWithString:str];
// 创建系统声音,同时返回一个ID
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &soundID);
// Register the sound completion callback.
AudioServicesAddSystemSoundCompletion(soundID,
NULL, // uses the main run loop
NULL, // uses kCFRunLoopDefaultMode
EMSystemSoundFinishedPlayingCallback, // the name of our custom callback function
NULL // for user data, but we don't need to do that in this case, so we just pass NULL
);
AudioServicesPlaySystemSound(soundID);
return soundID;
}
// 震动
- (void)playVibration
{
// Register the sound completion callback.
AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate,
NULL, // uses the main run loop
NULL, // uses kCFRunLoopDefaultMode
EMSystemSoundFinishedPlayingCallback, // the name of our custom callback function
NULL // for user data, but we don't need to do that in this case, so we just pass NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}