iOS Sound没有在Swift中播放

时间:2014-06-24 12:33:47

标签: ios iphone xcode swift avaudioplayer

我正在构建一个tableview,其中每个单元格代表当用户点击该特定单元格时播放的声音。

在Objective-C中它运行良好,但是现在Apple发布了Swift我决定立即移动,但由于某种原因声音不起作用。用户点击单元格时的代码:

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是必须调用的数组中的对象。我可以播放的每个声音都放在一个自定义对象中,连同标题和图像。该对象放在currentItem

的实例中

当我点击我的一个单元格时,这就是printNL输出的内容:

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

它不会出错。我已经尝试将声音文件移动到其他文件夹,但这也无法解决问题。因此,我认为发生此问题是因为我调用audioPlayer不正确?

任何帮助都将受到高度赞赏!

1 个答案:

答案 0 :(得分:2)

假设您有一个课程myTable:

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

...
}

初始化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()
        }
}

希望这有帮助。