Creating and playing a sound in swift - ios

So what I want to do is create and play a sound in swift that will play when I press a button, I know how to do it in Objective-C, but does anyone know how to in Swift?
It would be like this for Objective-C:
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"mysoundname" ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);
And then to play it I would do:
AudioServicesPlaySystemSound(Explosion);
Does anyone know how I could do this?

This is similar to some other answers, but perhaps a little more "Swifty":
// Load "mysoundname.wav"
if let soundURL = Bundle.main.url(forResource: "mysoundname", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
Note that this is a trivial example reproducing the effect of the code in the question. You'll need to make sure to import AudioToolbox, plus the general pattern for this kind of code would be to load your sounds when your app starts up, saving them in SystemSoundID instance variables somewhere, use them throughout your app, then call AudioServicesDisposeSystemSoundID when you're finished with them.

Here's a bit of code I've got added to FlappySwift that works:
import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}

Handy Swift extension:
import AudioToolbox
extension SystemSoundID {
static func playFileNamed(fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}
Then, from anywhere in your app (remember to import AudioToolbox), you can call
SystemSoundID.playFileNamed("sound", withExtenstion: "mp3")
to play "sound.mp3"

This creates a SystemSoundID from a file called Cha-Ching.aiff.
import AudioToolbox
let chaChingSound: SystemSoundID = createChaChingSound()
class CashRegisterViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
AudioServicesPlaySystemSound(chaChingSound)
}
}
func createChaChingSound() -> SystemSoundID {
var soundID: SystemSoundID = 0
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "Cha-Ching", "aiff", nil)
AudioServicesCreateSystemSoundID(soundURL, &soundID)
CFRelease(soundURL)
return soundID
}

With a class & AudioToolbox:
import AudioToolbox
class Sound {
var soundEffect: SystemSoundID = 0
init(name: String, type: String) {
let path = NSBundle.mainBundle().pathForResource(name, ofType: type)!
let pathURL = NSURL(fileURLWithPath: path)
AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect)
}
func play() {
AudioServicesPlaySystemSound(soundEffect)
}
}
Usage:
testSound = Sound(name: "test", type: "caf")
testSound.play()

import AVFoundation
var audioPlayer = AVAudioPlayer()
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
let soundURL = NSBundle.mainBundle().URLForResource("04", withExtension: "mp3")
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
audioPlayer.play()
}
}

This code works for me. Use Try and Catch for AVAudioPlayer
import UIKit
import AVFoundation
class ViewController: UIViewController {
//Make sure that sound file is present in your Project.
var CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds.mp3", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound)
audioPlayer.prepareToPlay()
} catch {
print("Problem in getting File")
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func button1Action(sender: AnyObject) {
audioPlayer.play()
}
}

var mySound = NSSound(named:"Morse.aiff")
mySound.play()
"Morse.aiff" is a system sound of OSX, but if you just click on "named" within XCode, you'll be able to view (in the QuickHelp pane) where this function is searching the sounds. It can be in your "Supporting files" folder

According to new Swift 2.0 we should use do try catch. The code would look like this:
var badumSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BadumTss", ofType: "mp3"))
var audioPlayer = AVAudioPlayer()
do {
player = try AVAudioPlayer(contentsOfURL: badumSound)
} catch {
print("No sound found by URL:\(badumSound)")
}
player.prepareToPlay()

this is working with Swift 4 :
if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}

//Swift 4
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
let path = Bundle.main.path(forResource: "note1", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
// error message
}
}
}

Let us see a more updated approach to this question:
Import AudioToolbox
func noteSelector(noteNumber: String) {
if let soundURL = Bundle.main.url(forResource: noteNumber, withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound)
}

import UIKit
import AudioToolbox
class ViewController: UIViewController {
let toneSound : Array = ["note1","note2","note3","note4","note5","note6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func playSound(theTone : String) {
if let soundURL = Bundle.main.url(forResource: theTone, withExtension: "wav") {
var mySound: SystemSoundID = 0
do {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
catch {
print(error)
}
}
}
#IBAction func anypressed(_ sender: UIButton) {
playSound(theTone: toneSound[sender.tag-1] )
}
}

You can try this in Swift 5.2
func playSound() {
let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}

For Swift 3:
extension SystemSoundID {
static func playFileNamed(_ fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}

Matt Gibson's solution worked for me, here is the swift 3 version.
if let soundURL = Bundle.main.url(forResource: "ringSound", withExtension: "aiff") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound);
}

Swift 4
import UIKit
import AudioToolbox
class ViewController: UIViewController{
var sounds : [SystemSoundID] = [1, 2, 3, 4, 5, 6, 7]
override func viewDidLoad() {
super.viewDidLoad()
for index in 0...sounds.count-1 {
let fileName : String = "note\(sounds[index])"
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: "wav") {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sounds[index])
}
}
}
#IBAction func notePressed(_ sender: UIButton) {
switch sender.tag {
case 1:
AudioServicesPlaySystemSound(sounds[0])
case 2:
AudioServicesPlaySystemSound(sounds[1])
case 3:
AudioServicesPlaySystemSound(sounds[2])
case 4:
AudioServicesPlaySystemSound(sounds[3])
case 5:
AudioServicesPlaySystemSound(sounds[4])
case 6:
AudioServicesPlaySystemSound(sounds[5])
default:
AudioServicesPlaySystemSound(sounds[6])
}
}
}
or
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
let soundURL = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
}

works in Xcode 9.2
if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}

Swift code example:
import UIKit
import AudioToolbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
// Load "mysoundname.wav"
if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
}

swift 4 & iOS 12
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
// noise while pressing button
_ = Bundle.main.path(forResource: "note1", ofType: "wav")
if Bundle.main.path(forResource: "note1", ofType: "wav") != nil {
print("Continue processing")
} else {
print("Error: No file with specified name exists")
}
do {
if let fileURL = Bundle.main.path(forResource: "note1", ofType: "wav") {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileURL))
} else {
print("No file with specified name exists")
}
} catch let error {
print("Can't play the audio file failed with an error \(error.localizedDescription)")
}
audioPlayer?.play() }
}

Use This Function to make sound in Swift (You can use this function where you want to make sound.)
First Add SpriteKit and AVFoundation Framework.
import SpriteKit
import AVFoundation
func playEffectSound(filename: String){
runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false))
}// use this function to play sound
playEffectSound("Sound File Name With Extension")
// Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3")

This code works for me:
class ViewController: UIViewController {
var audioFilePathURL : NSURL!
var soundSystemServicesId : SystemSoundID = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
audioFilePathURL = NSBundle.mainBundle().URLForResource("MetalBell", withExtension: "wav")
AudioServicesCreateSystemSoundID( audioFilePathURL, &soundSystemServicesId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func PlayAlertSound(sender: UIButton) {
AudioServicesPlayAlertSound(soundSystemServicesId)
}
}

Swift 3 here's how i do it.
{
import UIKit
import AVFoundation
let url = Bundle.main.url(forResource: "yoursoundname", withExtension: "wav")!
do {
player = try AVAudioPlayer(contentsOf: url); guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as Error {
print(error)
}
}

Couldn't you just import AVFoundation, select the audio player (var audioPlayer : AVAudioPlayer!), and play the sound? (let soundURL = Bundle.main.url(forResource: "sound", withExtension: "wav")

Related

unable to play sound on button pressed

I have the following code, I always get a breakpoint on "try btnSound". Not sure where I'm doing wrong. The Sound file is in main folder.
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var outputLbl: UILabel!
var btnSound: AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "btn", ofType: "wav")
do {
try btnSound = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
btnSound.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
}
#IBAction func numberPressed(btn: UIButton!){
btnSound.play()
}
}
OK. Thank you, people. I just used:
var audioPlayer = AVAudioPlayer()
let source = Bundle.main.path(forResource: "btn", ofType: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: source!))
audioPlayer.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
I renamed "path" to "sound" and it started working. Not sure what exactly the issue was.

I get the error: Value of type 'Bundle' has no member 'pathForResources'

Here is the code causing the error:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var BackgroundAudio = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: Bundle.mainBundle.pathForResources( "Music", ofType: "mp3")!),error: nil)
}
Edit:
I am creating a rock paper scissor game with audio here is my code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let backgroundAudio : AVAudioPlayer = {let url = Bundle.main.url(forResource: "Music", withExtension: "mp3")!
return try! AVAudioPlayer(contentsOf: url)
}()
let controller = ViewController()
controller.backgroundAudio.play()
#IBOutlet weak var cpuImage: UIImageView!
#IBOutlet weak var playerImage: UIImageView!
#IBOutlet weak var cpuScore: UILabel!
#IBOutlet weak var playerScore: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func rockButtonPressed(_ sender: Any) {
playerMove = 1
playerImage.image = UIImage(named: "playerRock.png")
computerChoice(cpuImage: cpuImage)
determineWinner(player: playerScore, cpu: cpuScore)
}
#IBAction func paperButtonPressed(_ sender: Any) {
playerMove = 2
playerImage.image = UIImage(named: "playerPaper.png")
computerChoice(cpuImage: cpuImage)
determineWinner(player: playerScore, cpu: cpuScore)
}
#IBAction func scissorButtonPressed(_ sender: Any) {
playerMove = 3
playerImage.image = UIImage(named: "playerScissor.png")
computerChoice(cpuImage: cpuImage)
determineWinner(player: playerScore, cpu: cpuScore)
}
}
Hope this helps
You are mixing up Swift 2 and 3 code and even in Swift 2 there is no pathForResources (plural) API.
If you are looking for an URL use the URL related API:
Bundle.main.url(forResource: "Music", withExtension: "mp3")
and the AVAudioPlayer initializer throws
do {
let url = Bundle.main.url(forResource: "Music", withExtension: "mp3")!
let backgroundAudio = try AVAudioPlayer(contentsOf: url)
} catch {
print(error)
}
In this case you can even write
let url = Bundle.main.url(forResource: "Music", withExtension: "mp3")!
let backgroundAudio = try! AVAudioPlayer(contentsOf: url)
because the initializer will succeed always (if it does not it's a design error).
Edit:
This is a way to create the audio player with a closure
class ViewController: UIViewController {
let backgroundAudio : AVAudioPlayer = {
let url = Bundle.main.url(forResource: "Music", withExtension: "mp3")!
return try! AVAudioPlayer(contentsOf: url)
}()
}
and play the sound
let controller = ViewController()
controller.backgroundAudio.play()
PS: Do not use NS... classes like NSURL if there is a native Swift counterpart (URL)
The function you are calling in your first line is not named like that anymore. Use this instead:
var BackgroundAudio = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: Bundle.main.path(forResource: "Music", ofType: "mp3")!),error: nil)

AVAudioPlayer doesn't play sound?

I have a AVAudioPlayer in a seperate class, which I load into a ViewController. Here's the code:
import Foundation
import AVFoundation
class SoundController {
var audioPlayer: AVAudioPlayer!
init() {
}
func playAudio() {
let path = NSBundle.mainBundle().pathForResource("ring-ring", ofType: "aiff", inDirectory: "Media" )!
let url = NSURL(fileURLWithPath: path)
do {
print("Let's play the sound")
let sound = try AVAudioPlayer(contentsOfURL: url)
self.audioPlayer = sound
sound.play()
} catch {
print("Error playing sound file")
}
}
}
And here is the ViewController
override func viewDidLoad() {
super.viewDidLoad()
let sound = SoundController()
sound.playAudio()
}
Everything compiles and I get the console output "Let's play the sound", but no matter which device I test on, the sound doesn't play. Any advice what's wrong?
You assign your audioPlayer the wrong way I think this should work.
import Foundation
import AVFoundation
var audioPlayer: AVAudioPlayer!
class SoundController {
class func playAudio() {
let path = NSBundle.mainBundle().pathForResource("ring-ring", ofType: "aiff", inDirectory: "Media" )!
let url = NSURL(fileURLWithPath: path)
do {
print("Let's play the sound")
audioPlayer = try AVAudioPlayer(contentsOfURL: url)
audioPlayer.prepareToPlay()
} catch {
print("Error playing sound file")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
SoundController.playAudio()
audioPlayer.play()
}

Playing an embedded sound using swift 2.0 code Xcode 7.1 IOS 9.1

Copied and Pasted this code principally. Compiles and runs, but plays nothing. Using Xcode 7.1 and IOS 9.1. What have I missed... Loaded sound file into main program and AVAssets...
import UIKit
import AVFoundation
class ViewController: UIViewController {
var buttonBeep : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
buttonBeep = setupAudioPlayerWithFile("hotel_transylvania2", type:"mp3")
//buttonBeep?.volume = 0.9
buttonBeep?.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
//1
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
//2
var audioPlayer:AVAudioPlayer?
// 3
do {
try audioPlayer? = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}
}
You've got this line backwards:
try audioPlayer? = AVAudioPlayer(contentsOfURL: url)
It should be:
audioPlayer = try AVAudioPlayer(contentsOfURL: url)
Side note: the conversion to and from NSString is not necessary here, just use String - and you should not force unwrap the result of NSBundle:
func setupAudioPlayerWithFile(file:String, type:String) -> AVAudioPlayer? {
//1
guard let path = NSBundle.mainBundle().pathForResource(file, ofType: type) else {
return nil
}
let url = NSURL.fileURLWithPath(path)
//2
var audioPlayer:AVAudioPlayer?
// 3
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}

AVAudioPlayer not playing audio in Swift

I have this code in a very simple, single view Swift application in my ViewController:
var audioPlayer = AVAudioPlayer()
#IBAction func playMyFile(sender: AnyObject) {
let fileString = NSBundle.mainBundle().pathForResource("audioFile", ofType: "m4a")
let url = NSURL(fileURLWithPath: fileString)
var error : NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
if (audioPlayer.isEqual(nil)) {
println("There was an error: (er)")
} else {
audioPlayer.play()
NSLog("working")
}
I have added import AVFoundation and audioPlayer is a global variable. When I execute the code, it does print "working", so it makes it through without errors but no sound is played. The device is not in silent.
There's so much wrong with your code that Socratic method breaks down; it will probably be easiest just to throw it out and show you:
var player : AVAudioPlayer! = nil // will be Optional, must supply initializer
#IBAction func playMyFile(sender: AnyObject?) {
let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()
}
I have not bothered to do any error checking, but the upside is you'll crash if there's a problem.
One final point, which may or may not be relevant: not every m4a file is playable. A highly compressed file, for example, can fail silently (pun intended).
Important that AvPlayer is class member and not in the given function, else it goes out of scope... :)
I had to declare a global player variable
var player: AVAudioPlayer!
and set it in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
player = AVAudioPlayer()
}
Then I could play the audio file wherever like this:
func playAudioFile(){
do {
if audioFileUrl == nil{
return
}
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: audioFileUrl, fileTypeHint: AVFileType.m4a.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
print("PLAYING::::: \(audioFileUrl)")
}
catch let error {
print(error.localizedDescription)
}
}
}
Here is a working snippet from my swift project. Replace "audiofile" by your file name.
var audioPlayer = AVAudioPlayer()
let audioPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audiofile", ofType: "mp3"))
audioPlayer = AVAudioPlayer(contentsOfURL: audioPath, error: nil)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
You can download fully functional Swift Audio Player application source code from here https://github.com/bpolat/Music-Player
for some reason (probably a bug) Xcode can't play certain music files in the .m4a and the .mp3 format I would recommend changing them all to .wav files to get it to play
//top of your class
var audioPlayer = AVAudioPlayer
//where you want to play your sound
let Sound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "wav")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: Sound as URL)
audioPlayer.prepareToPlay()
} catch {
print("Problem in getting File")
}
audioPlayer.play()
var audioPlayer = AVAudioPlayer()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("KiepRongBuon", ofType: "mp3")!)
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()
I used the below code in my app and it works. Hope that is helpful.
var audioPlayer: AVAudioPlayer!
if var filePath = NSBundle.mainBundle().pathForResource("audioFile", ofType:"mp3"){
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
audioPlayer.play()
}else {
println("Path for audio file not found")
}
In Swift Coding using Try catch, this issues will solve and play audio for me and my code below,
var playerVal = AVAudioPlayer()
#IBAction func btnPlayAction(sender: AnyObject) {
let fileURL: NSURL = NSURL(string: url)!
let soundData = NSData(contentsOfURL: fileURL)
do {
playerVal = try AVAudioPlayer(data: soundData!)
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down",error)
}
playerVal.delegate = self
playerVal.prepareToPlay()
playerVal.play()
}
Based on #matt answer but little bit detailed 'cause original answer did not completely satisfied me.
import AVFoundation
class YourController: UIViewController {
private var player : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
prepareAudioPlayer()
}
#IBAction func playAudio() {
player?.play()
}
}
extension YourController: AVAudioPlayerDelegate {}
private extension YourController {
func prepareAudioPlayer() {
guard let path = Bundle.main.path(forResource: "you-audio", ofType:"mp3") else {
return
}
let fileURL = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: fileURL)
} catch let ex {
print(ex.localizedDescription)
}
player?.prepareToPlay()
player?.delegate = self
}
}
swift 3.0:
import UIKit
import AVFoundation
class ViewController: UIViewController
{
var audioplayer = AVAudioPlayer()
#IBAction func Play(_ sender: Any)
{
audioplayer.play()
}
#IBAction func Pause(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.pause()
}
else
{
}
}
#IBAction func Restart(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.currentTime = 0
audioplayer.play()
}
else
{
audioplayer.play()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
do
{
audioplayer = try AVAudioPlayer(contentsOf:URL.init(fileURLWithPath:Bundle.main.path(forResource:"bahubali", ofType: "mp3")!))
audioplayer.prepareToPlay()
var audioSession = AVAudioSession.sharedInstance()
do
{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch
{
}
}
catch
{
print (error)
}
}
}

Resources