iOS Sound没有在Swift中播放 [英] iOS Sound not playing in Swift

查看:97
本文介绍了iOS Sound没有在Swift中播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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.

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

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

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

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!

推荐答案

假设你有一个课程myTable:

Let say you have a class 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()
        }
}

希望这有帮助。

这篇关于iOS Sound没有在Swift中播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆