简体   繁体   English

iOS声音无法在Swift中播放

[英]iOS Sound not playing in Swift

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. 在Objective-C中,它运行良好,但是现在苹果发布了Swift,我决定立即移动,但由于某种原因,声音无法播放。 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. currentItem是数组中必须调用的对象。 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 . 该对象放在currentItem的实例中。

This is what the printNL outputs when I tapp one of my cells: 这是我点击其中一个单元格时printNL输出的内容:

/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? 因此,我认为发生此问题的原因是我在调用audioPlayer不正确?

Any help would be highly appreciated! 任何帮助将不胜感激!

Let say you have a class myTable: 假设您有一个myTable类:

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

...
}

And to initialize audioPlayer : 并初始化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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM