我正在尝试在我的 iOS 应用中播放音频文件.这是我当前的代码
I'm trying to get an audio file playing in my iOS app. This is my current code
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];我一直在查看其他一些帖子,但它们通常都在做同样的事情.我没有收到错误消息,但我在模拟器或设备上听不到任何音频播放.
I've being checking a bunch of other posts but they all generally do the same thing. I'm not getting an error, but I don't hear any audio playing on the simulator or device.
这是我在模拟器上得到的音频文件的路径
This is the path I get for the audio file on the simulator
/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/long-numbered-thing/BookAdventure.app/test.m4a感谢任何帮助!
推荐答案也许你应该尝试使用 NSBundle 方法 pathForResource:ofType: 方法来创建路径文件.
Maybe you should try using the NSBundle method pathForResource:ofType: method to create the path to the file.
以下代码应该可以成功播放音频文件.我只将它与 mp3 一起使用,但我想它也应该与 m4a 一起使用.如果此代码不起作用,您可以尝试更改音频文件的格式.对于此代码,音频文件位于主项目目录中.
The following code should successfully play an audio file. I have only used it with an mp3, but I imagine it should also work with m4a. If this code does not work, you could try changing the format of the audio file. For this code, the audio file is located in the main project directory.
/* 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
Ok, so try this:
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];另外,请确保您进行了正确的导入:
Also, make sure you do the proper imports:
#import <AudioToolbox/AudioToolbox.h> #import <AVFoundation/AVFoundation.h>更多推荐
播放音频 iOS Objective
发布评论