AVAudioPlayer 不会播放 mp3 文件
AVAudioPlayer won't play an mp3 file
当我 运行 应用程序播放我的 MP3 文件时,我没有听到任何声音:"d.mp3"。
此文件在 iTunes 中播放正常。
我将 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
您必须在播放期间保留它,因为它不会保留自己。一旦解除分配,它将立即停止播放。
圆弧
您需要在 class 中持有 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
希望对您有所帮助
当我 运行 应用程序播放我的 MP3 文件时,我没有听到任何声音:"d.mp3"。 此文件在 iTunes 中播放正常。
我将 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
您必须在播放期间保留它,因为它不会保留自己。一旦解除分配,它将立即停止播放。
圆弧
您需要在 class 中持有 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
希望对您有所帮助