Audio file not playing for iOS 8 swift

Tags: audio swift ios8
By : sulz
Source: Stackoverflow.com
Question!

This is the code i'm using:

var aSound = NSURL(fileURLWithPath:  NSBundle.mainBundle().pathForResource("abc", ofType: "mp3"))

var audioPlayer = AVAudioPlayer()

        println(aSound)

        audioPlayer = AVAudioPlayer(contentsOfURL: aSound, error: nil)

        audioPlayer.prepareToPlay()

        audioPlayer.play()

I'm trying to print the path of the file and this is what I see in the console.

file:///Users/<username>/Library/Developer/CoreSimulator/Devices/<some GUID>/data/Containers/Bundle/Application/<some different GUID>/HelloWorld.app/abc.mp3

I have added the mp3 to my project by doing an "Add Files to project" from the menu. Does it get added to the location above automatically when I run the simulator?

By : sulz


Answers
var audio: AVAudioPlayer = AVAudioPlayer()

@IBAction func playaudio(sender: AnyObject) //method for playing audio {

var audioPath = NSString(string: NSBundle.mainBundle().pathForResource("bus", ofType: "mp3")!)

    var error: NSError? = nil

    //instantiate the player
    audio = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath as String), error: &error)
    audio.prepareToPlay()
    audio.play()
}

override func viewDidLoad() 
{

    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

And don't forget to import AVFoundation Framework.



import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fileName", ofType: "extension"))
        println(alertSound)
            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()
    }

}


Use This Function to make sound in Swift (You can use this function where you want to make sound.)

First Add SpriteKit Framework.

import SpriteKit
    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")
By : Raksha


This video can help you solving your question :)
By: admin