我可以使用AVAudioPlayer播放振动声音吗?

时间:2015-01-23 14:18:15

标签: ios avaudioplayer

我有AVAudioPlayer在聊天时播放消息提示音,我也想让手机振动。是否可以在AVAudioPlayer中执行此操作,还是需要使用其他方法?

由于

1 个答案:

答案 0 :(得分:5)

播放声音:

NSString *source = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"mp3"];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:source] error:nil];
self.audioPlayer.delegate = self;
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = 1.0; 
[self.audioPlayer play];

Swift 2.2版本:

var source = NSBundle.mainBundle().pathForResource("beep", ofType: "mp3")!
do {
    audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL.fileURLWithPath(source))
}
catch let error {
    // error handling
}
audioPlayer.delegate = self
audioPlayer.numberOfLoops = 0
audioPlayer.volume = 1.0
audioPlayer.play()

Swift 3.0版本:

var source = Bundle.main.path(forResource: "beep", ofType: "mp3")!
do {
    audioPlayer = try AVAudioPlayer(contentsOfURL: URL(fileURLWithPath: source))
}
catch {
    // error handling
}
audioPlayer.delegate = self
audioPlayer.numberOfLoops = 0
audioPlayer.volume = 1.0
audioPlayer.play()

振动:

AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

振动在Audiotoolbox.framework,播放声音在AVFoundation.framework

请注意,某些设备(iPod Touch)无法振动,这不会简单地工作。