objective-c - 播放音频 iOS Objective-C

标签 objective-c ios xcode audio

我正在尝试在我的 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

感谢任何帮助!

最佳答案

也许您应该尝试使用 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>

关于objective-c - 播放音频 iOS Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11525942/

相关文章:

ios - CollectionView 单元格中的间距

iOS:无法将 NextViewContrller 类型的值转换为 UINavigationController

ios - Cordova 使用 Xcode SQLite 插件构建

ios - ios中出现UISwipeGestureRecogniser时的UIImageView动画

objective-c - 无法让 [[id Animator] setAlphaValue : 0. 0] 工作

iphone - 从服务器保存和检索核心数据

ios - 应用程序更新需要考虑什么?

xcode - CoreBluetooth 框架和 IOBluetooth 框架的区别

objective-c - 这个 iOS 的属性分配是否正确?

ios - Flutter Xcode 构建失败 - 'TARGET_OS_WATCHOS' 未定义,计算结果为 0