早上好

如何编写代码以停止此代码中的多个音频文件

我正在寻找它,但没有发现任何有用的信息,请帮助我

import UIKit
import AVFoundation


class ViewController: UIViewController {

    let soundFilenames = ["001" , "002" , "003" , "004" , "005" , "006" , "007" , "008"]
    var Audios = [AVAudioPlayer]()




    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.




        for sound in soundFilenames {

            do {

                let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
                let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

                Audios.append(audioPlayer)


            }catch{

                Audios.append(AVAudioPlayer())

            }


        }

    }

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

    @IBAction func buttun001(sender: UIButton) {
       let audioplayer = Audios [sender.tag]
        audioplayer.play()

    }



   }

最佳答案

使用正常循环,检查是否正在播放并停止播放

func stopAudios(){
    for audioPLayer in Audios{
        if audioPLayer.playing{
            audioPLayer.stop()
        }
    }
}

同样不要忘记准备您的AVAudioPlayer
audioPlayer.prepareToPlay()

10-08 03:05