当我点击图像然后转到另一页时,我想播放声音

时间:2017-08-05 23:54:15

标签: image audio swift3

我想在点击第一张图片时播放任何声音,然后转到第二张图片页面。 This is the storyboard image of the specific part where I want the code to be based off of. 有人可以帮帮我吗。 如何将此代码添加到我的代码中 其他代码。有人用来帮助我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController , UIGestureRecognizerDelegate
{

@IBOutlet weak var imgPhoto: UIImageView!

override func viewDidLoad()
{


    super.viewDidLoad()
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(playSound(tapGestureRecognizer:)))
    imgPhoto.isUserInteractionEnabled = true
    imgPhoto.addGestureRecognizer(tapGestureRecognizer) /*Adding Gesture to image*/
}

/*
 This method is called when user tap on gesture and sound is played
 */
func playSound(tapGestureRecognizer: UITapGestureRecognizer)
{

    print("play")
        guard let url = Bundle.main.url(forResource:"a", withExtension: "mp3") else { return }
        do
        {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

            /*
             This method is used to notify when audio is completed
             */
           NotificationCenter.default.addObserver(self, selector: #selector(self.soundPlayComplete(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: url)

            player = try AVAudioPlayer(contentsOf: url)
            guard let player = player else { return }
            player.prepareToPlay()
            player.play()
            print("hhh")
        } catch let error {
            print(error.localizedDescription)
        }

}

func soundPlayComplete(sender: Notification) {
    print("Complete")
    //After completion audio you can perform segue here
}

}

我的代码我希望将其他代码添加到其中。

import UIKit
import AVFoundation

class ViewController: UIViewController {
class ViewController: UIViewController, UIGestureRecognizerDelegate {
    @IBOutlet weak var touchImageView: UIImageView!
}


let soundFilenames = ["5","8","7","4","6","1","3","2"]
var audioPlayers = [AVAudioPlayer]()
var lastAudioPlayer = 0

override func viewDidLoad() {
    super.viewDidLoad()



    // Do any additional setup after loading the view, typically from a nib.

    // Set up audio players
    for sound in soundFilenames {

        do {

            let url = URL(fileURLWithPath: Bundle.main.path(forResource: sound, ofType: "wav")!)
            let audioPlayer = try AVAudioPlayer (contentsOf:url)

            audioPlayers.append(audioPlayer)
        }
        catch {

                       audioPlayers.append(AVAudioPlayer())
        }
               }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func buttonTapped(_ sender: UIButton) {

    // Get the audioPlayer that corresponds to the button that they tapped
    let lastPlayer = audioPlayers[lastAudioPlayer]
    lastPlayer.stop();
    lastAudioPlayer = sender.tag;
    lastPlayer.currentTime = 0;
    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.currentTime=0;
    audioPlayer.play();
}

@IBAction func tbuttonTapped(_ sender: UIButton) {

    // Get the audioPlayer that corresponds to the button that they tapped

    let lastPlayer = audioPlayers[lastAudioPlayer]
    lastPlayer.stop();
    lastAudioPlayer = sender.tag;
    lastPlayer.currentTime = 0;
    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.currentTime=0;
    audioPlayer.play()

}

}

2 个答案:

答案 0 :(得分:0)

您需要在imageView上设置点击手势,然后使用AVAudioPlayer播放声音,然后执行AVAudioPlayer view controller using perform segue or using Bundle方法,该方法将在您调用后调用声音播放完毕,然后打开另一个customerPage

答案 1 :(得分:0)

首先你需要导入AVFoundation来播放声音(也不要忘记添加项目https://stackoverflow.com/a/9864504/6028575

 import UIKit
    import AVFoundation

    class ViewController: UIViewController , UIGestureRecognizerDelegate
    {

var player: AVAudioPlayer?

          @IBOutlet weak var touchImageView: UIImageView!

        override func viewDidLoad()
        {


            super.viewDidLoad()
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(playSound(tapGestureRecognizer:)))
            touchImageView.isUserInteractionEnabled = true
            touchImageView.addGestureRecognizer(tapGestureRecognizer) /*Adding Gesture to image*/
        }

        /*
         This method is called when user tap on gesture and sound is played
         */
        func playSound(tapGestureRecognizer: UITapGestureRecognizer)
        {

            print("play")
                guard let url = Bundle.main.url(forResource:"1", withExtension: "mp3") else { return }
                do
                {
                    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                    try AVAudioSession.sharedInstance().setActive(true)

                    /*
                     This method is used to notify when audio is completed
                     */
                   NotificationCenter.default.addObserver(self, selector: #selector(self.soundPlayComplete(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: url)

                    player = try AVAudioPlayer(contentsOf: url)
                    guard let player = player else { return }
                    player.prepareToPlay()
                    player.play()
                    print("hhh")
                } catch let error {
                    print(error.localizedDescription)
                }

        }

        func soundPlayComplete(sender: Notification) {
            print("Complete")
            //After completion audio you can perform segue here
        }

    }