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