如何加载和播放音频文件列表

时间:2016-01-16 09:54:23

标签: ios swift avfoundation

我有两个视图控制器collectionViewChildimageViewController。我在imageViewController中加载图片。现在在那个图像上,我有一个按钮,我想在每个图像上播放特定的声音。我知道如何播放单个音频但不知道如何选择特定声音并使用所需图像播放。

// collectionViewChild , here i want to display the image in the collectionviewChild



 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
            self.performSegueWithIdentifier("showDetailedImage", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ if segue.identifier == "showDetailedImage" {
            let indexPaths =           self.collectionViewChild!.indexPathsForSelectedItems()!
            let indexPath = indexPaths[0] as NSIndexPath
            let vc = segue.destinationViewController as! imageViewController
             vc.title = self.tableData[indexPath.row]
            vc.image = images[indexPath.row] as! UIImage
           }}}

//这是ImageViewController

import UIKit
import AVFoundation

class imageViewController: UIViewController {
@IBOutlet weak var imageView03: UIImageView!
    var selMake = UIImage()
  var image = UIImage()
     var audioPlayer = AVAudioPlayer()

// on this button i want to play the specific audio file
@IBAction func soundButton(sender: AnyObject) {
    let soundLocation = NSBundle.mainBundle().pathForResource("2", ofType: ".mp3")
     do {
    self.audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: soundLocation!))
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)
    }
    catch {
    print("Something bad happened. Try catching specific errors to narrow things down")
    }
    self.audioPlayer.prepareToPlay()
    self.audioPlayer.play()
    }
    else { print("") }

override func viewDidLoad() {
        self.imageView03.image = self.image
        super.viewDidLoad()
    }

1 个答案:

答案 0 :(得分:0)

有多个音频播放器的助手类会不会有帮助吗?我制作了一个简单的音频播放器类,可以轻松扩展多个音轨。

你可以从gitHub获取我的助手 https://github.com/crashoverride777/Swift2-Music-Helper

按下图像时,您可以使用按钮方法播放相应的声音。

Music.sharedInstance.playImage1()
Music.sharedInstance.playImage2()

...

你可以将其与上面的Mohameds评论结合起来。

这是你在找什么?