N.echizen
N.echizen

Reputation: 49

Swift - How to pause a playing audio by clicking the same button?

So I have a list of audio files and when a cell is pressed it plays the audio. This works fine but I am not able to pause it by clicking the same cell again.

My code for the table view:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    let a = indexPath.section;
    let b = indexPath.row;

    var path = NSBundle.mainBundle().pathForResource(musicArray[b], ofType: "mp3")
    var error:NSError?

    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
    }
    catch
    {
        print("Something bad happened")
    }

    if (audioPlayer.playing)
    {
        audioPlayer.pause();
    }
    else
    {
        audioPlayer.play();
    }
}

musicArray has the titles of the audio files

Upvotes: 0

Views: 1193

Answers (2)

T. Pasichnyk
T. Pasichnyk

Reputation: 732

You can create a singleton object.

import AVFoundation
class SomeAudioManager: NSObject, AVAudioPlayerDelegate
{
    class var sharedInstance: SomeAudioManager {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: SomeAudioManager? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SomeAudioManager()
        }
        return Static.instance!
    }
    func audioView(songname: String,format: String) {
        let audioPlayer: AVAudioPlayer

        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(songname, ofType:format)!), fileTypeHint: AVFileTypeMPEGLayer3)
            audioPlayer.delegate = self;
            audioPlayer.play()
        } catch {
            // error
        }
    }
}

It will be alive through the whole app.

How to implement AVAudioPlayer Inside Singleton Method?

You can just create a singleton of the player so that you will always know if it's playing or not.

Upvotes: 0

TylerP
TylerP

Reputation: 9829

You're creating a new AVAudioPlayer every time you select the cell. You need to keep a reference to the previous one and tell that audio player to pause.

Upvotes: 1

Related Questions