【问题标题】:cocoa playing an mp3可可播放 mp3
【发布时间】:2010-07-18 17:51:33
【问题描述】:

有没有一种简单的方法可以从 cocoa 加载、播放和控制 mp3 文件?试着用谷歌搜索它,但是,就像苹果一样,我得到了混乱的结果,不知道从哪里开始。据我了解,有 NSSound,但它有很多限制,然后有 CoreAudio,但这非常困难。那么有人可以指出我正确的方向吗?谢谢。

【问题讨论】:

  • 抱歉,您是为 iOS 还是 Mac 开发?
  • 是的,抱歉,忘了说明:AVAudioPlayer 不起作用:我正在为 OSX 开发
  • 从 Mac OS X 10.7 Lion 开始(甚至可能是 10.6.8?)AVFoundation 有效!因此,AVAudioPlayer .. 请参阅下面的答案..

标签: objective-c cocoa macos mp3 playback


【解决方案1】:

复活进行中:

为什么要复活这个问题?因为谷歌搜索“可可播放 mp3”把我带到了这里,而且 2012 年没有很棒的答案。所以,这是 2012 年的精彩答案;)

使用 AVFoundation!根据苹果的说法,它已经与 Mac OS X Lion 集成(我认为),所以.. 以下是如何轻松播放 mp3:

1- 链接 AVFoundation 框架。

2- 将它导入到任何你想播放精彩 mp3 的地方

#import <AVFoundation/AVFoundation.h>

3- 添加一个 audioPlayer 实例变量来播放声音(至少我喜欢这样做)

@interface WCMainWindow : ... {
    ...
    AVAudioPlayer* 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- 播放您的精彩 Mp3!

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

最后,感谢 this guy

【讨论】:

  • 你如何测试才能知道你是否能够使用这个?
  • 什么意思?完成说明的步骤,并确保将 MP3 文件添加到资源中。然后,添加一个将调用[audioPlayer play] 的按钮(操作)
  • URLWithString 方法总是为我返回 nil。改用[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"mp3"]]; 解决了这个问题。
【解决方案2】:

我用 C++ 编写了一个可能有帮助的框架:http://github.com/sbooth/SFBAudioEngine

它支持多种音频格式,并具有相当良性的 API,并附带一个 Cocoa 示例。

如果您对第三方框架不感兴趣,您可能会选择使用 AudioQueue 来处理播放。为此,您可能会使用 AudioFile 来解码 MP3 和 AudioQueue 以进行播放。苹果在http://developer.apple.com/mac/library/samplecode/AudioQueueTools/Introduction/Intro.html有一个例子

【讨论】:

    【解决方案3】:

    使用NSSound

    您没有具体说明“很多限制”是什么意思,所以我不知道为什么这对您不起作用。请注意,自 Leopard 以来,它的限制要少得多。例如,您现在可以在任何设备上播放。

    【讨论】:

      【解决方案4】:
      #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
      

      【讨论】:

        【解决方案5】:

        除了NSSound,您还可以考虑QTMovieView。这听起来很奇怪,但您可以在窗口中隐藏QTMovieView 并用它来播放 MP3。

        添加:QTMovieView 自 OS 10.9 起已弃用。因此,除非您需要支持 10.7 之前的操作系统版本(当 AVFoundation 来到 Mac 时),否则您可能不应该使用它。

        【讨论】:

        • 我也看到了没有任何视图的 QTKit 示例,但我不确定这是否是一个好方法,因为我还没有找到如何查找文件甚至可能稍后添加一些效果。
        • 我不确定您所说的“查找文件”是什么意思。
        • 嗯,简单来说,去某个特定的位置,然后从那里继续玩。
        • 哦,好的……在使用QTMovieView的时候,可以在关联的QTMovie上使用setCurrentTime:等QTMovie方法。
        • 谢谢。 QTMovie以后可以加一些音效吗?像混响,均衡器等?还是只有 CoreAudio 才有可能?
        【解决方案6】:
        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.
                }
            }
            
            
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-24
          • 1970-01-01
          • 2015-01-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多