Kex
Kex

Reputation: 8609

Can I play a sound with vibrate using AVAudioPlayer?

I have AVAudioPlayer playing a sound for a message alert during chat, I also want the phone to vibrate. Is it possible to do this in AVAudioPlayer or do I need to use a different method?

Thanks

Upvotes: 2

Views: 1840

Answers (1)

KlimczakM
KlimczakM

Reputation: 12934

To play a sound:

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 version:

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 version:

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()

To vibrate:

AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

Vibration is in Audiotoolbox.framework and playing a sound is in AVFoundation.framework.

Please note that some devices (iPod Touch) cannot vibrate and this won't simply work.

Upvotes: 5

Related Questions