我正在尝试在我的 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
method 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];
EDIT
好的,那么试试这个:
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)