Playing a sound with AVAudioPlayer
101,452
Solution 1
Made modification to your code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))
println(alertSound)
// Removed deprecated use of AVAudioSessionDelegate protocol
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Swift 3 and Swift 4.1:
import UIKit
import AVFoundation
class ViewController: UIViewController {
private var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "button-09", ofType: "wav")!)
print(alertSound)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try! audioPlayer = AVAudioPlayer(contentsOf: alertSound)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
}
Solution 2
As per Swift 2 the code should be
var audioPlayer : AVAudioPlayer!
func playSound(soundName: String)
{
let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)
do{
audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
audioPlayer.prepareToPlay()//there is also an async version
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
Solution 3
Your audio play will be deallocated right after viewDidLoad finishes since you assign it to a local variable. You need to create a property for it to keep it around.
Solution 4
The solution is for AudioPlayer which has play/pause/stop button in the navigation bar as bar button items
In Swift 2.1 you can use the below code
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let audioPath = NSBundle.mainBundle().pathForResource("ARRehman", ofType: "mp3")
var error:NSError? = nil
do {
player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down")
}
}
@IBAction func play(sender: UIBarButtonItem) {
player.play()
}
@IBAction func stop(sender: UIBarButtonItem) {
player.stop()
print(player.currentTime)
player.currentTime = 0
}
@IBAction func pause(sender: UIBarButtonItem) {
player.pause()
}
@IBOutlet weak var sliderval: UISlider!
@IBAction func slidermov(sender: UISlider) {
player.volume = sliderval.value
print(player.volume)
}
}
Solution 5
This will work.....
import UIKit
import AVFoundation
class ViewController: UIViewController {
var ding:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
prepareAudios()
ding.play()
}
func prepareAudios() {
var path = NSBundle.mainBundle().pathForResource("ding", ofType: "mp3")
ding = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: nil)
ding.prepareToPlay()
}
}
Author by
user3722523
Updated on December 30, 2020Comments
-
user3722523 over 3 years
I'm trying to play a sound with
AVAudioPlayer
but it won't work.Edit 1: Still doesn't work.
Edit 2: This code works. My device was in silent mode.
import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav")) println(alertSound) var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error) audioPlayer.prepareToPlay() audioPlayer.play() } }
-
blue over 9 yearsHi, I'm trying to add sound to my program using about the same code and it is crashing. Where exactly do u put the audio file? In the assets folder or..?
-
vladof81 over 9 years@skyguy, you may drag the sound file to your project and select the proper target to add.
-
danielsalare over 9 yearsany ideas on how to use it for pls or remote mp3 files?
-
Ruben Martinez Jr. over 9 years@edse for remote mp3 file, initialize your alertSound like
var alertSound = NSURL(string: "http://my-file-url.com/song.mp3")
-
danielsalare over 9 yearsWill this work for streaming? I was trying the following with a pls ulr stackoverflow.com/questions/26075618/…
-
danielsalare over 9 yearsI just tried this with a remote mp3 file and a pls file but it doesn't play any sound. If I use a local file works perfectly.
-
houguet pierre over 9 years"The AVplayer doesn't provide support for streaming, you can with AVPlayer stackoverflow.com/questions/3635792/…
-
Prudhvi about 9 years"This will work" But why it will work? Please explain what's wrong with OP and how you resolved it so that future users can understand the concept behind it.
-
confile about 9 yearsDo I have to create a new instance of
AVAudioPlayer
for each sound file I will play? -
Ray over 8 yearsThis may "work", but it does not preload audio and my result in negative performance when first executed
-
Khaled Annajar over 8 years@Alexsander This is how: stackoverflow.com/questions/24393495/…
-
scrrr about 8 yearsYou should make audioPlayer an instance variable somewhere. This code will have it deallocated immediately after calling .play() and you won't hear a thing.
-
AppreciateIt almost 8 yearsThe app will also experience a slight lag because it needs to load the file and prepare the player all at once.
-
coding22 over 6 yearsmake audioPlayer an instance variable
-
Hardik Thakkar over 5 yearsI got error in prepareAudioSession function... did you face this issue in iOS 12.
-
Johhn almost 5 yearsAnyone else with some weird issue as mine, "just not working after copy pasting the code, ensure proper location and import of your files in the build phase" and the code above should thereafter work