Swift:音频文件数组

时间:2016-07-01 00:27:22

标签: arrays xcode swift audio

使用Swift 2如何创建要在集合视图上使用的音频文件数组?

共有4个选项" Ocean"," Birds"," Nature"," Waves"它们显示为单元格。

单击一个单元格时,我需要它来播放声音。你能帮忙吗?

    var imageArray = [UIImage(named: "ocean"),UIImage(named: "birds"),UIImage(named: "nature"),UIImage(named: "wave")]
var nameArray = ["Ocean","Birds","Nature","Waves"]



func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.imageArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! homeCollectionViewCell

    cell.iconImage?.image = imageArray[indexPath.item!]
    cell.label.text = nameArray[indexPath.item!]

    return cell
}

2 个答案:

答案 0 :(得分:0)

你知道如何播放声音吗?你做完了吗? 如果是这样,您需要使用以下函数并执行以下操作:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //grab the sound from the array
        let sound = your_array_with_sounds[indexPath.row]

        //if you want to play the sound in this view:
           <code to play the sound>          
        //if you want to play the sound in another view:
           <perform the segue and pass the sound to the view you want>
    }

我希望这有帮助。如果没有,请在您的问题中添加更多信息,我们会帮助您。

答案 1 :(得分:0)

您需要使用AVAudioPlayer类播放音频 为此,您需要导入以下类

导入AVFoundation

您需要使用以下代码

创建函数
let audioName:String!


func playAudio(){
    let url = NSURL.fileURLWithPath(
                NSBundle.mainBundle().pathForResource(audioName, 
                ofType: "mp3")!)

        var error: NSError?

        audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)

        if let err = error {
            println("audioPlayer error \(err.localizedDescription)")
        } else {
            audioPlayer?.delegate = self
            audioPlayer?.prepareToPlay()
        }
      if let player = audioPlayer {
               player.play()
       }
}
集合视图中的

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{
          audioName = arrayName[indexPath.row]
}

Swift 4.0

let audioName:String!
func playAudio(){
    let url = NSURL.fileURL(
        withPath: Bundle.main.path(forResource: audioName,
                                              ofType: "mp3")!)
    var error: NSError?

    let audioPlayer = try? AVAudioPlayer(contentsOf: url)
    audioPlayer?.delegate = self
    audioPlayer?.prepareToPlay()

    if let player = audioPlayer {
        player.play()
    }
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{
          audioName = arrayName[indexPath.row]
}