AVAudioPlayer不会播放MP3文件
问题描述:
当我运行应用程序时,当应用程序播放我的MP3文件时,我听不到任何声音:“d.mp3”。 此文件在iTunes中可以播放。AVAudioPlayer不会播放MP3文件
我将AVFoundation.framework添加到项目中。 添加文件“d.mp3”到项目。
添加到浏览器:
#import <UIKit/UIKit.h>
#import "AVFoundation/AVAudioPlayer.h"
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Play an MP3 file:
printf("\n Play an MP3 file");
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"d"
ofType:@"mp3"]];
printf("\n url = %x", (int)url);
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:nil];
printf("\n audioPlayer = %x", (int)audioPlayer);
[audioPlayer play];
}
输出日志:
Play an MP3 file
url = 3ee78eb0
audioPlayer = 3ee77810
答
非ARC
你必须在播放期间留住它,因为它不保留本身。一旦它被解除分配,它将立即停止播放。
ARC
您需要在类中保存AVAudioPlayer实例。并停止播放后释放它。例如,
#import <AVFoundation/AVFoundation.h>
@interface YourController() <AVAudioPlayerDelegate> {
AVAudioPlayer *_yourPlayer; // strong reference
}
@end
@implementation YourController
- (IBAction)playAudio:(id)sender
{
NSURL *url = [[NSBundle mainBundle] URLForResource:@"d" withExtension:@"mp3"];
_yourPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
_yourPlayer.delegate = self;
[_yourPlayer play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (player == _yourPlayer) {
_yourPlayer = nil;
}
}
@end
希望这有助于
+0
它只有在将playAudio的内容移动到viewDidLoad后才有效。 –
+0
好的,意味着代码就是你要找的东西? – gurmandeep
也许尝试通过一个非空参数传递给'错误:'参数,看看它试图告诉你问题是什么? –
我不相信AVAudioPlayers会保留自己,这意味着玩家可能会立即被释放。你能把它存储在一个强大的实例变量上,看看它是否有效? – Msencenb
请勿使用'printf'和'%x'。使用'NSLog'和'%@'。这会给你提供更多有用的信息,指针地址! – jcaron