Play audio and vibration simultaneously on ios using swift - ios

Is there any way to play audio file and vibrate iphone when audio is started and stop vibrating when audio stops playing?
currently this code is working but it plays audio and when audio stops then it vibrates the phone, I want both (audio and vibration) play together.
var alertSoundEffect: AVAudioPlayer?
let path = Bundle.main.path(forResource: "alert.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
alertSoundEffect = try AVAudioPlayer(contentsOf: url)
alertSoundEffect?.prepareToPlay()
alertSoundEffect?.play()
} catch {
return
}
let vib = SystemSoundID(1519)
AudioServicesPlayAlertSound(SystemSoundID(vib))
AudioServicesRemoveSystemSoundCompletion(vib)

You can try
DispatchQueue.global().async
{
var alertSoundEffect: AVAudioPlayer?
let path = Bundle.main.path(forResource: "alert.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
alertSoundEffect = try AVAudioPlayer(contentsOf: url)
alertSoundEffect?.prepareToPlay()
alertSoundEffect?.play()
} catch {
return
}
}

Related

Play a sound file on repeat in Swift?

I have had success playing sounds by pressing a button, by using the following code. However, I'd like to press a button and have that sound play in a loop/infinitely. How is this acheived? I'd also like to acheive pause/play functionality as well. Thanks in advance.
#IBAction func keyPressed(_ sender: UIB`utton) {
playSound(soundName: sender.currentTitle!)
}
func playSound(soundName: String) { //
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
} // End of Play Sound
By default AVAudioPlayer plays its audio from start to finish then stops, but we can control how many times to make it loop by setting its numberOfLoops property. For example, to make your audio play three times in total, you’d write this:
player.numberOfLoops = 3
if you want the infinite loop then use
player.numberOfLoops = -1
for e.g
func playSound(soundName: String) { //
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.numberOfLoops = -1 // set your count here
player.play()
} // End of Play Sound
var audioPlayer: AVAudioPlayer?
func startBackgroundMusic() {
if let bundle = Bundle.main.path(forResource: "Guru_Nanak_Sahib_Ji", ofType: "mp3") {
let backgroundMusic = NSURL(fileURLWithPath: bundle)
do {
audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
guard let audioPlayer = audioPlayer else { return }
audioPlayer.numberOfLoops = -1 // for infinite times
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
You can retain the player. Then in the player's completion delegate callback, start playing again. Or stop the player at any time, since you've retained a reference to it.

How to play sound using media volume instead of ring volume in ios?

I am trying to play a sound but my current code bases the volume off of the ringtone volume. How to I change this to media volume?
var player: AVAudioPlayer?
...
func playSound(name: String) {
let url = Bundle.main.url(forResource: name, withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
...
playSound(name: "baby")
Only set that before you put some url into the player.
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
To play sound using media volume you should do like this:
func play(){
let path = Bundle.main.path(forResource: "Plop", ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
bombSoundEffect = sound
sound.play()
} catch {
// couldn't load file :(
}
}

Swift 3.0 AVAudioPlayer Playing audio over music

Currently this is the code I'm using to play my sound during the button press.
var player: AVAudioPlayer?
let url = Bundle.main.url(forResource: "Sound/yatch", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
Im trying to get this audio to run over whats currently playing (etc Spotify, pandora, Music). How would I go about doing this?
Set the audio session of your application to play over the currently playing audio:
try? AVAudioSession.sharedInstance().setActive(true)
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
According to the AVAudioSession headers, AVAudioSessionCategoryAmbient will play audio with music, etc.
/* Use this category for background sounds such as rain, car engine noise, etc.
Mixes with other music. */
public let AVAudioSessionCategoryAmbient: String
Swift 5.3 Update
guard let url = Bundle.main.url(forResource: "INSERT_FILENAME", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
audioPlayer.volume = 1
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}

AVAudioSession/AVQueuePlayer/AVAudioPlayer in the Background Swift

Problem: I am trying to get my audio to continue to play even when the app is in the background. The desired result would be that the audio continues to play even when: the home button is pressed, the phone sleeps/is locked, and to be able to mix with the other sounds (native music app, etc). I have looked at the other examples and have tried implementing them but without success. After starting the app action, my app plays a short sound and then waits a period of time, which it then plays another sound.
Things I have tried -
AVAudioPlayer not responding in the background
How to Play Audio in Background Swift?
Things I have learned so far is that I probably want to use the AVAudioSession with the Ambient category so that my sound mixes with the native music app. I have turned on the background capabilities in the tab and in the plist. I have tried putting the AVAudioSession in multiple places (delegate/VC file).
I am using the code from #2 to start my audioSession. Here is the code that plays the sound
func playComboSound(fileName:String){
if(fileName != "burpees" && fileName != "pushUps" && fileName != "sitUps")
{
let url = NSBundle.mainBundle().URLForResource(fileName, withExtension: "mp3")!
do {
appDelegate.audioPlayer = try AVAudioPlayer(contentsOfURL: url)
//guard let appDelegate.audioPlayer = audioPlayer else { return }
//appDelegate.audioPlayer!.stop()
appDelegate.audioPlayer!.prepareToPlay()
appDelegate.audioPlayer!.play()
} catch let error as NSError {
print(error.description)
}
}
else
{
let numRepAudio: String
switch numReps{
case "THREE":
numRepAudio = "three"
case "FIVE":
numRepAudio = "five"
case "TEN":
numRepAudio = "ten"
default:
numRepAudio = "three"
}
let url1 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(numRepAudio, ofType: "mp3")!)
let url2 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(fileName, ofType: "mp3")!)
print(numRepAudio)
print(fileName)
let item1 = AVPlayerItem(URL: url1)
let item2 = AVPlayerItem(URL: url2)
let items: [AVPlayerItem] = [item1, item2]
appDelegate.playerQueue = AVQueuePlayer(items: items)
appDelegate.playerQueue!.play()
}
}
Thank you

Play audio file in a sequence in swift

I have two functions. First one loops list of names for audio to be played, and the second one is the actual player function. The problem is that it plays only the last one. It does not play one by one waiting till the next is finished. How it possible to perform in a sequence? I tried to add: dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), { }) ... still does not work. Any possible solution. Thank you in advance!
func startGame(){
audioPlay("NowListen")
for i in 0...self.soundArray.count - 1 {
print(self.soundArray[i])
self.audioPlay(self.soundArray[i])
}
}
func audioPlay(name: String){
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("\(name)", ofType: "mp3")!)
print(alertSound)
// try to play sound
do{
self.audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
self.audioPlayer.prepareToPlay()
self.audioPlayer.play()
} catch {
}
}
Use AVQueuePlayer ( init it with Items at the start and it will play in queue, one after another ) class instead of AVAudioPlayer.
In your Start Game, you can do following:
var audioItems: [AVPlayerItem] = []
for audioName in soundsArray {
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(audioName, ofType: "mp3")!)
let item = AVPlayerItem(URL: url)
audioItems.append(item)
}
let player = AVQueuePlayer(items: audioItems)
player.play()

Resources