0

My app plays mp3 files in sequence. I finally managed to play mp3 files in sequence. Additionally, I need to show simple text on my app depending on the mp3 file.

For example, when 0.mp3 file is played, textlabel.text shows "hello" from textarray. after the 0.mp3 is played, when 1.mp3 file is played, textlabel.text shows "nice to meet you" from textarray.

How to show simple sentences on the text label depending on the audio file, one after another?

textarray = ["hello" , "nice to meet you" , "my name is James" , "how old are you?"]

@IBAction func autoplay(_ sender: Any) {

    var items : [AVPlayerItem] = []
    for number in myIndex..<arr.count {
        let url = Bundle.main.url(forResource: String(number), withExtension: "mp3")!
        items.append(AVPlayerItem(url: url))
        textlabel.text = textarry[number]

    }
     queue = AVQueuePlayer(items: items)
    queue.play()
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
mjk
  • 21
  • 1
  • 6

1 Answers1

3

It is mentioned in many answers here on how to get a callback when a video item finishes playing. One way to show the relevant video text is as below,

@IBAction func autoplay(_ sender: Any) {

    var items : [AVPlayerItem] = []
    for number in myIndex..<arr.count {
        let url = Bundle.main.url(forResource: String(number), withExtension: "mp3")!
        items.append(AVPlayerItem(url: url))
    }
    queue = AVQueuePlayer(items: items)
    queue.play()

    textlabel.text = textarry[myIndex]
}


override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(onVideoComplete),
        name: .AVPlayerItemDidPlayToEndTime,
        object: nil)

}   

@objc func onVideoComplete() {
    if let currentTitle = textlabel.text, let currentIndex = textarry.firstIndex(of: currentTitle) {
        self.textlabel.text = textarry[currentIndex.advanced(by: 1)]
    }
}
Kamran
  • 14,987
  • 4
  • 33
  • 51
  • Thank you! They match first but after that, all files and the sentences don't match. – mjk Oct 22 '19 at 11:51
  • Well, you have to put a breakpoint inside `onVideoComplete` and see what `currentTitle` and `currentIndex` you are getting. First make sure, `onVideoComplete` method is called everytime a video is finished playing. – Kamran Oct 22 '19 at 11:53
  • I checked and currentIndex increases per 2. not 1. like, 6->8->10->12->14 and so on. I'm not sure how to fix it because I'm very new to Swift. – mjk Oct 24 '19 at 10:15
  • You must be changing `textlabel` text somewhere else? – Kamran Oct 24 '19 at 10:40
  • Thank you so much. it works so well. My mistake. I put " NotificationCenter.default.addObserver( self, selector: #selector(onVideoComplete), name: .AVPlayerItemDidPlayToEndTime, object: nil) " two times and that was why my app wasn't working properly. the code that you wrote works so well. I really appreciate that. – mjk Oct 25 '19 at 01:54