gpt4 book ai didi

iOS 声音无法在 Swift 中播放

转载 作者:行者123 更新时间:2023-11-28 05:34:47 25 4
gpt4 key购买 nike

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

在 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 不正确?

非常感谢任何帮助!

最佳答案

假设您有一个类 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 声音无法在 Swift 中播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24386766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com