iOS Sound not playing in Swift

走远了吗. 提交于 2019-12-31 04:51:29

问题


I'm building a tableview in which each cell represents a sound that is played when the user taps that particular cell.

In objective-C it worked fine, but now that Apple released Swift I decided to move over instantly, but for some reason the sound does not play. My code when the user taps the cell:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    var currentItem = self.items[indexPath.row]

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

    println(audioPath)

    var audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: nil)
    audioPlayer.play()
}

currentItem is the object in the array that has to be called. Each sound I can play is put in a custom object, together with a title and an image. that object is put in an instance of currentItem.

This is what the printNL outputs when I tapp one of my cells:

/private/var/mobile/Containers/Bundle/Application/ADF0CAFC-4C9E-475E-B3F0-CD85A1873CA5/Juichen.app/StupidQuestion.mp3

it does not give an error. I already tried moving the sound file to other folders, but that does not solve the problem either. therefore, I assume that this problem occurs because I am calling the audioPlayer incorrect?

Any help would be highly appreciated!


回答1:


Let say you have a class myTable:

class myTable : UITableViewController
{
    var audioPlayer:AVAudioPlayer? = nil

...
}

And to initialize audioPlayer:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) 
{
        var currentItem = self.items[indexPath.row]

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

        println(audioPath)

        var error : NSError? = nil
        self.audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)

        if (self.audioPlayer == nil)
        {
            if let playerError = error as? NSError
            {
                let des : String? = playerError.localizedDescription
                println("Error: \(des)")
            }
        }
        else
        {
            self.audioPlayer.play()
        }
}

Hope this helps.



来源:https://stackoverflow.com/questions/24386766/ios-sound-not-playing-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!