【问题标题】:Play Audio iOS Objective-C播放音频 iOS Objective-C
【发布时间】:2012-07-16 13:51:52
【问题描述】:

我正在尝试在我的 iOS 应用中播放音频文件。这是我当前的代码

NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a", [[NSBundle mainBundle] resourcePath]];

NSLog(@"%@",soundFilePath);
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[audioPlayer setVolume:1.0];

audioPlayer.delegate = self;

[audioPlayer stop];
[audioPlayer setCurrentTime:0];
[audioPlayer play];

我正在检查一堆其他帖子,但它们通常都做同样的事情。我没有收到错误消息,但我没有听到模拟器或设备上播放任何音频。

这是我在模拟器上获取音频文件的路径

/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/long-numbered-thing/BookAdventure.app/test.m4a

感谢任何帮助!

【问题讨论】:

  • 尝试另一个音频文件,test.m4a 可能已损坏,这就是它无法播放的原因。
  • audioPlayer 是否指向有效对象?静音开关是否打开?设备音量调高了吗?
  • 我很确定这是一个有效的对象。有没有办法判断路径是否正确?我认为如果它是空对象或无效路径会引发错误。静音开关未打开并且设备音量已打开@Jeremy1026 该文件在 xCode 和我的 MBP 上正常播放,所以我认为这很好
  • 你在这个项目中使用 ARC 吗?
  • 你明白了吗? @Lagoo87

标签: objective-c ios xcode audio


【解决方案1】:

也许你应该尝试使用NSBundle 方法pathForResource:ofType: 方法来创建文件的路径。

以下代码应该可以成功播放音频文件。我只将它与mp3 一起使用,但我想它也应该与m4a 一起使用。如果此代码不起作用,您可以尝试更改音频文件的格式。对于此代码,音频文件位于项目主目录中。

/* Use this code to play an audio file */
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test"  ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite

[player play];

编辑

好的,试试这个:

NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a",[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite

[player play];

另外,请确保您执行正确的导入:

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

【讨论】:

  • 当我这样做时,我的 soundFilePath 最终是 (null)...?我的文件在主项目目录中。在 xCode 中,它位于“音频”组下,我认为这并不重要。
  • 你可以试试我的代码,但是使用你的路径创建方法(例如 NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a", [[NSBundle mainBundle] resourcePath]];)反而。另外,您的 soundFilePath 的 NSLog 会打印什么?
  • 每次都打印声音文件路径(null)当我使用这种其他路径创建方法时,我的 soundFilePath 显示“file://localhost/Users/userName/Library/Application%20Support/iPhone%20Simulator /5.1/Applications/long-number-thing-here/BookAdventure.app/test.m4a"
  • 已经有正确的导入。奇怪,.mp3 有效,但 .m4a 无效。不知道为什么,但很高兴我能播放一些音频!
  • 这些 sn-ps 不需要 FYI AudioToolbox 导入 :)
【解决方案2】:

您需要存储对“AVAudioPlayer”的strong引用

@property (strong) AVAudioPlayer *audioPlayer;

如果您确定您的音频文件在以下捆绑资源中,它应该可以播放。

项目>构建阶段>复制

【讨论】:

  • 我遇到了几乎相同的问题,并确保我保留对播放器对象的引用解决了问题。使用Url 等创建播放器的方式的哪种变体不是问题,而只是对播放器的引用随着实例化的方法/范围的完成而丢失的事实。
【解决方案3】:

播放扩展名为 .caf、.m4a、.mp4、.mp3、.wav、.aif 的文件


GitHub下载以下两个文件

SoundManager.h
SoundManager.m

将这些文件添加到您的项目中

还将音频文件添加到资源文件夹 (sample files)

mysound.mp3, song.mp3

在需要的文件中导入头文件

#import "SoundManager.h"

并在 -(void)viewDidLoad

中添加以下两行
[SoundManager sharedManager].allowsBackgroundMusic = YES;
[[SoundManager sharedManager] prepareToPlay];

使用以下行播放声音 (mysound.mp3)

[[SoundManager sharedManager] playSound:@"mysound" looping:NO];

使用以下行停止声音 (mysound.mp3)

[[SoundManager sharedManager] stopSound:@"mysound"];

您还可以将音乐 (song.mp3) 播放为

[[SoundManager sharedManager] playMusic:@"song" looping:YES];

并且可以停止音乐为

[[SoundManager sharedManager] stopMusic];

填写Documentation is on GitHub

【讨论】:

  • 在上述方法中添加.FileExtension(例如:@"mysound.mp3"):)
  • 你试过没有扩展名吗?它应该自动从资源中检测声音文件
  • 是的,我试过不带扩展名,但它无法检测到文件。也许是因为我在 xcode 6.x 中使用它,它没有检测到。不知道 xcode 7x。
【解决方案4】:

首先将此框架导入到您的文件中

#import <AVFoundation/AVFoundation.h>

然后声明AVAudioPlayer的实例。

AVAudioPlayer *audioPlayer;

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Name of your audio file" 
                                                          ofType:@"type of your audio file example: mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];

【讨论】:

  • 很酷的示例,最低限度,例如,具有适当的功能。稍微澄清一下 numbnerOfLoopsCounting:(-1) - 代表无穷大,0 - 代表一,依此类推。我添加了一个 UIButton 来运行 [audioPlayer play]; 但这取决于用户如何处理代码。从简洁和用户便利的角度来看,我支持您的回答!谢谢!
【解决方案5】:

如果您生成系统声音 ID,则使用以下代码播放您的捆绑音频文件

for(int i = 0 ;i< 5;i++)
{
    SystemSoundID   soundFileObject;
    NSString *audioFileName = [NSString stringWithFormat:@"Alarm%d",i+1];

    NSURL *tapSound   = [[NSBundle mainBundle] URLForResource: audioFileName
                                            withExtension: @"caf"];

    // Store the URL as a CFURLRef instance
    CFURLRef soundFileURLRef = (__bridge CFURLRef) tapSound;

    // Create a system sound object representing the sound file.
    AudioServicesCreateSystemSoundID (

                                  soundFileURLRef,
                                  &soundFileObject
                                  );
    [alarmToneIdList addObject:[NSNumber numberWithUnsignedLong:soundFileObject]];
}

您可以使用以下代码播放声音

AudioServicesPlaySystemSound([[alarmToneIdList objectAtIndex:row]unsignedLongValue]);

要实现这个下面的框架需要在你的 Xcode 中添加

音频工具箱

最后需要在控制器中导入以下头文件

#import AudioToolbox/AudioToolbox.h
#import AudioToolbox/AudioServices.h

【讨论】:

    【解决方案6】:

    为 Swift 4 更新 从主包播放 - 仅限 iOS 11

    import AVFoundation
    
    var player: AVAudioPlayer?
    

    以下代码加载并播放声音文件,必要时返回错误。

    guard let url = Bundle.main.url(forResource: "test", withExtension: "m4a") else { return }
    
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
    
        guard let player = player else { return }
    
        player.play()
    
        } catch let error {
            // Prints a readable error
            print(error.localizedDescription)
        }
    

    【讨论】:

      【解决方案7】:

      斯威夫特 4.2

      var soundFilePath = "\(Bundle.main.resourcePath ?? "")/test.m4a"
      var soundFileURL = URL(fileURLWithPath: soundFilePath)
      
      var player = try? AVAudioPlayer(contentsOf: soundFileURL)
      player?.numberOfLoops = -1 //Infinite
      
      player?.play()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-17
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 2020-05-27
        • 1970-01-01
        • 2023-04-03
        相关资源
        最近更新 更多