我正在尝试构建一个应用程序存储用户可以播放的特定声音。我向你保证我已经搜索了2天,但我找不到我想要的东西。 (或者我不能成功地使用那些蠢货)
应用程序商店的声音如下:
var sound1 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Adios Amigos", ofType: "mp3")!)
var sound2 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "ses2", ofType: "mp3")!)
var sound3 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "ses3", ofType: "mp3")!)
var sound4 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "ses4", ofType: "mp3")!)
var soundArray: [NSURL] = [sound1, sound2, sound3, sound4]
这是我的按钮,播放声音随机:
@IBAction func Rastgele(sender: Any) {
let randNo = Int(arc4random_uniform(UInt32(soundArray.count))) // 0...ArrayCount
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOf: (soundArray[randNo] as NSURL) as URL)
audioPlayer.prepareToPlay()
audioPlayer.play()
self.sesLabel.text = soundArray[randNo].deletingPathExtension?.lastPathComponent
soundIndex = randNo} catch {
print(error)
}
}
这是我的IBAction按钮,我无法填写代码。
@IBAction func Favori(_ sender: Any) {
// empty
}
我尝试使用NSUserdefaults,但我无法达到我想要的效果。 我也试图从我的数组中拉出数组项来插入另一个数组,但由于数组类型(NSURL)我遇到了很多问题
所以,'Favori'按钮应存储为收藏夹然后我可以在其他表视图中显示收藏的声音。
提前致谢。
修改
我找到了一个使用Core Data并将NSURL转换为URL的解决方案。感谢@rmaddy的有用评论。工作代码在下面;
@IBAction func Favori(_ sender: Any) {
// save core data
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let newSound = NSEntityDescription.entity(forEntityName: "Sounds", in: context)
let sound = NSManagedObject(entity: newSound!, insertInto: context)
sound.setValue(soundArray[soundIndex].deletingPathExtension().lastPathComponent, forKey: "soundName")
do { try context.save()
soundItems.append(sound)
print(sound)
}
catch
{
print("error")
}
}
答案 0 :(得分:0)
单击按钮时,使用sqlite或服务器将URL保存到core data或local data base。 如果您只想将其传递给另一个tableview而不保存它(当您杀死该应用时数据会丢失),您可以使用delegate或notification center传递它。