基本上,我正在尝试构建一个音乐播放器应用程序,以便学习iOS平台和Swift 3,但我目前只是坚持一个简单的步骤。我正在尝试创建一个类型歌曲的数组,并在歌曲艺术家之后追加该数组的歌曲名称等。
该功能也需要修改。我之前使用过一系列名称,但之后我决定创建这个结构。
import Foundation
struct Song {
var _songTitle:String?
var _songArtist:String?
var _songDuration:Double?
var _songCover:String?
}
import AVFoundation
类AudioManager:NSObject,AVAudioPlayerDelegate {
static let sharedInstance = AudioManager()
var currentSong = 0
var currentTime = 0
var player: AVAudioPlayer = AVAudioPlayer()
private override init() {}
private var songs: [Song] = []
func play()
{
player.play()
}
func stop() {
if player.isPlaying{
player.stop()
}
}
func playThis()
{
do
{
guard let audioPath = Bundle.main.path(forResource: songs._songTitle?[currentSong], ofType: ".mp3")
else {
return
}
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath) as URL)
}
catch
{
print ("ERROR")
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
{
if flag {
currentSong += 1
}
if ((currentSong + 1) == songs.count) {
currentSong = 0
}
}
func skipForward() {
var timeToSkip: TimeInterval = player.currentTime
timeToSkip += 5.0
player.currentTime = timeToSkip
}
func skipBack() {
var timeToSkip: TimeInterval = player.currentTime
timeToSkip -= 5.0
player.currentTime = timeToSkip
}
func gettingSongNames()
{
let folderURL = URL(fileURLWithPath:Bundle.main.resourcePath!)
do
{
let songPath = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
//loop through the found urls
for song in songPath
{
var mySong = song.absoluteString
if mySong.contains(".mp3")
{
let findString = mySong.components(separatedBy: "/")
mySong = findString[findString.count-1]
mySong = mySong.replacingOccurrences(of: "%20", with: " ")
mySong = mySong.replacingOccurrences(of: ".mp3", with: "")
song._songTitle.append(mySong)
}
}
}
catch
{
print ("ERROR")
}
}
}
答案 0 :(得分:0)
您可以在AudioManager
类实例中添加一个方法来执行添加歌曲,如下所示:
func addSong(song: Song) {
songs.append(song)
}
你可以像这样使用它:
let song = Song(_songTitle: "Title", _songArtist: "Artist", _songDuration: 0, _songCover: "Cover")
AudioManager.sharedInstance.addSong(song: song)
你不能song._songTitle.append(mySong)
,因为_songTitle
是一个字符串,而不是一个数组。如果要进行追加,则必须将其声明为数组。
答案 1 :(得分:0)
您正在以错误的顺序组合struct member access和array indexing。例如,您有一个song
类型的数组[Song]
,这是一组歌曲,并且可以访问您编写的特定标题:
songs._songTitle?[currentSong]
其中说“songs
具有数组值属性_songTitle
,访问其currentSong
元素” - 这是向后的。您需要首先访问数组元素,返回Song
,然后返回属性:
songs[currentSong]._songTitle
您似乎也希望创建一个仅指定标题的新歌曲。要做到这一点,你应该在init
上添加Song
方法:
init(withTitle: String) { ... }
将新歌曲的标题设置为提供的值,将其他属性设置为nil
。 (如果您不了解init
方法,请参阅Apple的Swift书。)
一旦你有了这个初始化器,就会添加一首新歌:
songs.append( Song(withTitle:mySong) )
HTH