在iOS中播放多首歌曲

时间:2017-01-08 11:01:34

标签: ios swift avaudioplayer

我为iOS编写了这段代码来播放一首歌,但是我不知道如何编写代码来播放多首歌曲。

这是一首歌的代码行:

------+---------------------+---------------------+------------+------+------------+-----------+----------+----------+---------------------+---------------------+----------------+
| id   | startdatetime       | enddatetime         | d_dte      | Rule | Dte        | StartTime | EndTime  | WageRate | newst               | newet               | TimeDifference |
+------+---------------------+---------------------+------------+------+------------+-----------+----------+----------+---------------------+---------------------+----------------+
|    1 | 2016-12-31 23:30:00 | 2017-01-01 06:30:00 | 2016-12-31 |    1 | 2016-12-31 | 07:00:00  | 23:59:00 |       25 | 2016-12-31 23:30:00 | 2016-12-31 23:59:00 | 00:29:00       |
|    2 | 2016-12-31 23:30:00 | 2017-01-01 06:00:00 | 2016-12-31 |    1 | 2016-12-31 | 07:00:00  | 23:59:00 |       25 | 2016-12-31 23:30:00 | 2016-12-31 23:59:00 | 00:29:00       |
|    1 | 2016-12-31 23:30:00 | 2017-01-01 06:30:00 | 2017-01-01 |    2 | 2017-01-01 | 00:00:00  | 06:00:00 |       40 | 2017-01-01 00:00:00 | 2017-01-01 06:00:00 | 06:00:00       |
|    2 | 2016-12-31 23:30:00 | 2017-01-01 06:00:00 | 2017-01-01 |    2 | 2017-01-01 | 00:00:00  | 06:00:00 |       40 | 2017-01-01 00:00:00 | 2017-01-01 06:00:00 | 06:00:00       |
|    1 | 2016-12-31 23:30:00 | 2017-01-01 06:30:00 | 2017-01-01 |    3 | 2017-01-01 | 06:00:00  | 11:30:00 |       30 | 2017-01-01 06:00:00 | 2017-01-01 06:30:00 | 00:30:00       |
+------+---------------------+---------------------+------------+------+------------+-----------+----------+----------+---------------------+---------------------+----------------+
5 rows in set (0.05 sec)

2 个答案:

答案 0 :(得分:1)

实际上,您只需使用两个AVAudioPlayer实例即可播放它。如果你想同时播放它们,每个声音文件都需要它自己的AVAudioPlayer。

答案 1 :(得分:0)

我已经写了一个答案,所以即使已经有了正确答案,我也会发帖。帕尔梅说的是对的。您可以使用多个AVAudioPlayer实例同时播放多个声音:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    let paths = ["a","b"]
    var sounds = [AVAudioPlayer]()

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

        for path in paths {

            do
            {
                let audioPath = Bundle.main.path(forResource: path, ofType: "mp3")

                let player = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)

                sounds.append(player)

            }
            catch
            {
                //ERROR
            }

        }

        for sound in sounds {
            sound.play()
        }
    }
}