使用集合视图单元格按钮在项目中播放声音 - Swift
Play Sounds in the Project with Collection View Cell Buttons - Swift
我正在尝试在点击按钮时播放我的项目文件中的声音。
Button 连接到 CollectionViewCell,这是重复的,所以我无法在我的 ViewController 上创建插座。
相反,我在我的 ViewController 上放了一个动作插座,以便在点击按钮时播放声音。
let musicFile = Bundle.main.path(forResource: "\(soundNames["\(sender.currentTitle)"])", ofType: "mp3")
我在这里要做的是;我的按钮已经根据我之前创建的数组命名,所以如果我能得到按钮的名称,那肯定是一个.mp3文件在我的项目中并且可以播放。
但是上面提供的代码行给我错误:
Cannot subscript a value of type '[String]' with an index of type 'String'
我怎样才能完成这项工作?如有必要,我可以提供更多代码。
提前致谢。
摆脱 "\(...)"
符号。你不在这里打印;您正在传递一个实际的字符串。直接使用实际值来形成该字符串。这种事情可能会奏效:
let index = 0 // getting the _real_ number is the issue, perhaps
let title = soundNames[index]
let musicFile = Bundle.main.path(forResource: title, ofType: "mp3")
但实际上,这完全取决于 soundNames
的构造方式,您没有显示。
我正在尝试在点击按钮时播放我的项目文件中的声音。
Button 连接到 CollectionViewCell,这是重复的,所以我无法在我的 ViewController 上创建插座。
相反,我在我的 ViewController 上放了一个动作插座,以便在点击按钮时播放声音。
let musicFile = Bundle.main.path(forResource: "\(soundNames["\(sender.currentTitle)"])", ofType: "mp3")
我在这里要做的是;我的按钮已经根据我之前创建的数组命名,所以如果我能得到按钮的名称,那肯定是一个.mp3文件在我的项目中并且可以播放。
但是上面提供的代码行给我错误:
Cannot subscript a value of type '[String]' with an index of type 'String'
我怎样才能完成这项工作?如有必要,我可以提供更多代码。
提前致谢。
摆脱 "\(...)"
符号。你不在这里打印;您正在传递一个实际的字符串。直接使用实际值来形成该字符串。这种事情可能会奏效:
let index = 0 // getting the _real_ number is the issue, perhaps
let title = soundNames[index]
let musicFile = Bundle.main.path(forResource: title, ofType: "mp3")
但实际上,这完全取决于 soundNames
的构造方式,您没有显示。