cocoa playing an mp3

Viewed 12299

Is there an easy way to load, play and control an mp3 file from cocoa? Tried googling it, but, as all things apple, i get messy results and have no idea where to start. As i understand, there's and NSSound, but it has lots of limitations and then there's CoreAudio, but it's very difficult. So can someone point me in a right direction with this? Thanks.

6 Answers

Use AVFoundation! According to apple, it has been integrated with Mac OS X Lion (I think), so.. Here is how to play mp3 painlessly:

1- link the AVFoundation Framework.

2- import it wherever you want to play your awesome mp3

#import <AVFoundation/AVFoundation.h>

3- Add an audioPlayer instance variable to play the sound (That's how I like to do it, at least)

@interface WCMainWindow : ... {
    ...
    AVAudioPlayer* audioPlayer;
}

4- In you init, make sure you initialize your audioPlayer:

NSString* path = [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"mp3"];
NSURL* file = [NSURL fileURLWithPath:path];
// thanks @gebirgsbaerbel
    
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
[audioPlayer prepareToPlay];

5- Play your awesome Mp3!!

if ([audioPlayer isPlaying]) {
    [audioPlayer pause];
} else {
    [audioPlayer play];
}

Finally, credit goes to this guy.

import Cocoa
import AVFoundation

class ViewController: NSViewController {
    
    
    var audio = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let play = Bundle.main.path(forResource: "A" , ofType: "mb3")
        do{
            audio = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: play!))
        }
        catch{
            print(error)
        }
        
    }
    
    
    @IBAction func button(_ sender: Any)
    {
        audio.play()
    }
    
    override var representedObject: Any? {
        didSet {
            // Update the view, if already loaded.
        }
    }
    
    
}
Related