2016-07-01 51 views
1

使用Swift 2我將如何創建一個音頻文件數組以用於集合視圖?Swift:音頻文件數組

有4個選項「海洋」,「鳥類」,「自然」,「波浪」,它們顯示爲單元格。

當單擊單元格時,我需要它播放聲音。你能幫忙嗎?

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 
} 
+0

y在哪裏y你想播放音頻嗎?相同的'viewController'或導航到不同的? – Santosh

+0

viewcontroller @Santosh –

+0

您是否實現了'didSelectRowAtIndexPath'方法?如果沒有,那麼你應該使用它來執行任何操作來選擇'tableView'中的特定'cell'。因此,創建一個更多的音頻文件陣列,並在音頻文件數組中使用'indexPath.row'獲取音頻文件。 – Santosh

回答

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> 
    } 

我希望這幫助。如果沒有,請在您的問題中添加更多信息,我們會爲您提供幫助。

+0

嗨,對不起,如果我不清楚我知道如何播放聲音,我需要的是一系列聲音你知道嗎?謝謝@Amandeu_Andrade –

+0

你是否想從某個地方發出請求來下載聲音,或者你是否有聲音並將它們導入到項目中? –

+0

我有他們會導入他們請我只需要一個音頻文件或聲音數組@Amadeu_Andrade –

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] 
} 
+1

Swift的當前版本是2.2,即將推出3款。你真的應該避免發佈在Swift 1中的答案,這不是很有用。 :) – Moritz