简体   繁体   English

可可播放 mp3

[英]cocoa playing an mp3

Is there an easy way to load, play and control an mp3 file from cocoa?有没有一种简单的方法可以从可可加载、播放和控制 mp3 文件? 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.据我所知,有和 NSSound,但它有很多限制,然后有 CoreAudio,但它非常困难。 So can someone point me in a right direction with this?那么有人可以指出我正确的方向吗? Thanks.谢谢。

RESURRECTION IN PROGRESS:正在进行中的复活:

Why resurrect this question?为什么要复活这个问题? because Googling "cocoa playing mp3" Takes me here, and there is no awesome 2012 answer.因为谷歌搜索“可可播放 mp3”将我带到这里,并且没有很棒的 2012 答案。 So, here is the awesome 2012 answer ;)所以,这是 2012 年很棒的答案;)

Use AVFoundation!使用 AVFoundation! According to apple, it has been integrated with Mac OS X Lion (I think), so.. Here is how to play mp3 painlessly:据苹果称,它已与 Mac OS X Lion 集成(我认为),所以.. 以下是如何轻松播放 mp3:

1- link the AVFoundation Framework. 1- 链接 AVFoundation 框架。

2- import it wherever you want to play your awesome mp3 2- 将其导入到任何您想播放精彩 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) 3- 添加一个 audioPlayer 实例变量来播放声音(至少我喜欢这样做)

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

4- In you init, make sure you initialize your audioPlayer: 4- 在初始化时,确保初始化音频播放器:

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!! 5- 播放您的精彩 Mp3!

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

Finally, credit goes to this guy .最后,功劳归于这个人

I've written a framework in C++ that might help: http://github.com/sbooth/SFBAudioEngine我用 C++ 编写了一个可能有帮助的框架: http : //github.com/sbooth/SFBAudioEngine

It supports multiple audio formats and has a fairly benign API and comes with a Cocoa sample.它支持多种音频格式,并具有相当良性的 API 并带有 Cocoa 示例。

If you're not interested in third-party frameworks, your bet would probably be to use an AudioQueue to take care of the playback.如果您对第三方框架不感兴趣,您可能会选择使用 AudioQueue 来处理播放。 To do this, you'd probably use AudioFile to decode the MP3 and AudioQueue for the playback.为此,您可能会使用 AudioFile 来解码 MP3 和 AudioQueue 以进行播放。 Apple has an example at http://developer.apple.com/mac/library/samplecode/AudioQueueTools/Introduction/Intro.html Apple 在http://developer.apple.com/mac/library/samplecode/AudioQueueTools/Introduction/Intro.html有一个例子

#import <Cocoa/Cocoa.h>
#import <QTKit/QTKit.h>

@interface SoundPlayer : NSObject {
  NSSound *sound;
  IBOutlet NSWindow *window;
  IBOutlet NSSlider *progress;
  BOOL loop;
}
- (IBAction)open: (id)sender;
- (IBAction)setLoop: (id)sender;
- (IBAction)play: (id)sender;
- (IBAction)stop: (id)sender;
- (IBAction)takeCurrentTimeFrom: (id)sender;
@end

#import "SoundPlayer.h"

@implementation SoundPlayer
- (IBAction)open: (id)sender
{
    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    [openPanel runModalForTypes: [NSArray arrayWithObjects: @"aiff", @"mp3", @"m4a", nil]];
    [sound release];
    sound = [[QTMovie movieWithFile: [openPanel filename]
                              error: NULL] retain];
    [sound setAttribute: [NSNumber numberWithBool: loop]
                 forKey: QTMovieLoopsAttribute];
    [window setTitle: [[openPanel filename] lastPathComponent]];
}
- (IBAction)setLoop: (id)sender
{
    loop = ([sender state] == NSOnState);
    [sound setAttribute: [NSNumber numberWithBool: loop]
                 forKey: QTMovieLoopsAttribute];
}
- (IBAction)play: (id)sender
{
    NSTimeInterval duration;
    QTGetTimeInterval([sound duration], &duration);
    [progress setMaxValue: duration];
    [NSTimer scheduledTimerWithTimeInterval: 0.1
                                     target: self
                                   selector: @selector(updateIndicator:)
                                   userInfo: sound
                                    repeats: YES];
    [sound play];
}
- (void)updateIndicator: (NSTimer*)aTimer
{
    QTMovie *playingSound = [aTimer userInfo];
    if (!(sound == playingSound && ([sound rate] != 0)))
    {
        [aTimer invalidate];
        return;
    }
    NSTimeInterval currentTime;
    QTGetTimeInterval([sound currentTime], &currentTime);
    [progress setDoubleValue: currentTime];
}
- (IBAction)stop: (id)sender
{
    [sound stop];
}
- (IBAction)takeCurrentTimeFrom: (id)sender
{
    [sound setCurrentTime: QTMakeTimeWithTimeInterval([sender doubleValue])];
}
@end

Use NSSound .使用NSSound

You didn't specify what you mean by “lots of limitations”, so I don't know why this won't work for you.您没有具体说明“很多限制”是什么意思,所以我不知道为什么这对您不起作用。 Note that it has a lot fewer limitations since Leopard;请注意,自 Leopard 以来,它的限制要少得多; you can now play to any device, for example.例如,您现在可以在任何设备上播放。

Besides NSSound , you could consider QTMovieView .除了NSSound ,你可以考虑QTMovieView It sounds odd, but you can have a hidden QTMovieView in your window and use it to play an MP3.这听起来很奇怪,但是您可以在窗口中隐藏QTMovieView并用它来播放 MP3。

Added: QTMovieView is deprecated as of OS 10.9.补充: QTMovieView从 OS 10.9 开始被弃用。 So unless you need to support OS versions before 10.7 (when AVFoundation came to the Mac), you should probably not use this.因此,除非您需要支持 10.7 之前的操作系统版本(当 AVFoundation 出现在 Mac 上时),您可能不应该使用它。

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.
        }
    }
    
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM