Play a sound file on repeat in Swift? - ios

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.

Related

How do I play an audio file from Swift File Manager?

I'm trying to play a file I downloaded from S3, after locating the file and passing the URL to the audio player, the audio file won't play/is missing.
This is the complete fileURL: file:///var/mobile/Containers/Data/Application/61F2FC20-4C62-4263-B147-0010805BC0FA/Documents/Dump%20Trucks.mp3
Here is my code:
func playAudio(){
var soundClip: AVAudioPlayer?
if let directory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first{
let path = NSURL(fileURLWithPath: directory).appendingPathComponent("Dump Trucks.mp3")
print("The path is \(String(describing: path))")
do {
soundClip = try AVAudioPlayer(contentsOf: path!)
soundClip?.play()
} catch {
print("Error: Audio File missing.")
}
}
}
The problem is that your player is a local variable. Thus your method comes to an end and the player is destroyed before it ever has a chance to start playing! Declare it as an instance property instead.
So
func playAudio(){
var soundClip: AVAudioPlayer?
Becomes
var soundClip: AVAudioPlayer?
func playAudio(){
This might not solve all your problems but if you don’t do it you certainly will never hear sound.
import Foundation
import AVFoundation
final class MediaPlayer {
static var player = AVAudioPlayer()
class func play() {
do {
let file = Bundle.main.url(forResource: "file_name", withExtension: "mp3")!
player = try AVAudioPlayer(contentsOf: file)
player.numberOfLoops = 0 // loop count, set -1 for infinite
player.volume = 1
player.prepareToPlay()
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
try AVAudioSession.sharedInstance().setActive(true)
player.play()
} catch _ {
print("catch")
}
}
}

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

Play different audioplayers in sequence Swift

So basically I have two audio players while using the AVFoundation. I want the second one to be played right after the first one finishes.
myFilePathString = NSBundle.mainBundle().pathForResource("\(workout[currentExercise])", ofType: "mp3")
#IBAction func startWorkout(sender: AnyObject) {
if let myFilePathString = myFilePathString {
let myFilePathURL = NSURL(fileURLWithPath: myFilePathString)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: myFilePathURL)
audioPlayer.play()
}catch {
print("Error")
}
}
This above one is to be the first
let path = NSBundle.mainBundle().pathForResource("Rest", ofType: "mp3")
let url = NSURL(fileURLWithPath: path!)
do {
let sound = try AVAudioPlayer(contentsOfURL: url)
secondAudioPlayer = sound
sound.play()
} catch {
print("error")
}
...while this one is to be played after. At the moment they play at the same time. Got any ideas for me?
Thank you in advance.

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