AVAudioPlayer不能播放mp3文件吗?

3

我想让我的 AVAudioPlayer 播放一些 mp3 文件。它可以播放其中的一些文件,但有一个文件无法播放!

为了播放该文件,我将其下载到设备上的应用程序文件夹中,并以以下方式初始化:

[[AVAudioPlayer alloc] initWithContentsOfURL:soundPath error:nil];

如何播放这个文件?为什么它不能播放?

文件链接:abc.mp3

编辑:

(以下是显示错误的代码。代码内有README说明,请在设备上尝试。)

***.pch

#import <Availability.h>

#ifndef __IPHONE_4_0
#warning "This project uses features only available in iOS SDK 4.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <SystemConfiguration/SystemConfiguration.h>
    #import <MobileCoreServices/MobileCoreServices.h>
    #import <AVFoundation/AVFoundation.h>
    #import <AudioToolbox/AudioToolbox.h>
#endif



ViewController.h

#import <UIKit/UIKit.h>
#import "AFNetworking.h"

@interface SCRViewController : UIViewController <AVAudioPlayerDelegate>
{
    UIButton *button;
    __block UIProgressView *view;
    NSOperationQueue *queue;
    __block BOOL isFile;
    UIButton *play;
    NSString *path;
    AVAudioPlayer *_player;
}

@end


ViewController.m

#import "ViewController.h"

@implementation SCRViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundColor:[UIColor yellowColor]];
    [button setFrame:CGRectMake(50, 50, 220, 50)];
    [button addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Download" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [self.view addSubview:button];

    play = [UIButton buttonWithType:UIButtonTypeCustom];
    [play setBackgroundColor:[UIColor yellowColor]];
    [play setFrame:CGRectMake(50, 150, 220, 50)];
    [play addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
    [play setTitle:@"Play" forState:UIControlStateNormal];
    [play setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [play setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [self.view addSubview:play];

    self->view = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self->view.frame = CGRectMake(10, 120, 300, 20);
    [self->view setProgress:0];
    [self.view addSubview:self->view];

    queue = [[NSOperationQueue alloc] init];

    isFile = NO;
}

- (void) download
{
    [button setBackgroundColor:[UIColor brownColor]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    [button setEnabled:NO];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://iwheelbuy.com/abc.mp3"]];

    //-------------------------------------------------------
    //-------------------------------------------------------
    // READ ME
    //-------------------------------------------------------
    //-------------------------------------------------------
    // Test in on device
    // I have uploaded another song for you. You can change link to http://iwheelbuy.com/def.mp3 and check the result
    // def.mp3 works fine on the device
    //-------------------------------------------------------
    //-------------------------------------------------------

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    path = [path stringByAppendingPathComponent:@"song"];

    if ( [[NSFileManager defaultManager] fileExistsAtPath:path])
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];

    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         isFile = YES;
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         //
     }];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
     {
         CGFloat done = (CGFloat)((int)totalBytesRead);
         CGFloat expected = (CGFloat)((int)totalBytesExpectedToRead);
         CGFloat progress = done / expected;
         self->view.progress = progress;
     }];
    [queue addOperation:operation];
}

- (void) play
{
    if (isFile)
    {
        NSError *error = nil;
        NSURL *url = [NSURL fileURLWithPath:path];
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        if(error || !_player)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[error description] delegate:nil cancelButtonTitle:@"Try def.mp3" otherButtonTitles:nil];
            [alert show];
        }
        else
        {
            [_player play]; // plays fine
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[AVAudioSession sharedInstance] setActive: YES error: nil];
        }
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Download the file plz" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
    }
}

@end

可能是重复的问题:AVAudioPlayer无法加载声音 - jrc
2个回答

7

非 ARC

在播放期间,您需要保留它,因为它不会自己保留。一旦它被删除,则立即停止播放。

ARC

您需要在类中持有AVAudioPlayer实例,并在其停止播放后释放它。例如:

#import <AVFoundation/AVFoundation.h>

@interface TAViewController () <AVAudioPlayerDelegate> {
    AVAudioPlayer *_somePlayer;   // strong reference
}
@end

@implementation TAViewController

- (IBAction)playAudio:(id)sender
{
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"kogmawjoke" withExtension:@"mp3"];
    _somePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    _somePlayer.delegate = self;
    [_somePlayer play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (player == _somePlayer) {
        _somePlayer = nil;
    }
}

@end

其他歌曲都播放得很好!只有这首不想播放! - iWheelBuy
我在iPhone 4S(iOS6)和iOS6模拟器中尝试了您的音频,但都无法播放。您能否提供有关测试环境的更多信息? - HKTonyLee
你已经将这首歌下载到你的设备/模拟器上了吗?还是你使用了这首歌的直链? - iWheelBuy
我已经下载了它到项目中。编译时将其复制到 .app 中。然后使用 NSBundle 来获取文件的路径。 - HKTonyLee
嗯...我在应用程序运行期间下载它。并将其保存在应用程序的文档文件夹中。也许这就是问题所在?! - iWheelBuy

1
http://bugreport.apple.com

根据以下信息,工程师已确定此问题的行为符合预期:

可以使用附加的示例应用程序进行复制,但这是来自AudioFile的预期行为。

问题在于AVAudioPlayer使用没有文件扩展名的URL进行初始化,相应的文件没有有效的ID3标签。没有文件扩展名或有效数据,我们无法确定正确的文件格式,因此这些文件将无法打开。这是一种预期的行为。

在附加的示例代码中:

path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

path = [path stringByAppendingPathComponent:@"song"];

--> 路径将类似于:

/var/mobile/Applications/2FFD0147-E56B-47D4-B143-A9F19BE92818/Documents/song

--> 注意:结尾没有文件扩展名。

abc.mp3的ID3标签大小无效(0x2EE),而def.mp3具有有效的标签大小(0x927)。因此,当它们被指定为“…./song”时,没有任何扩展名,AudioFile只查看数据并找到def.mp3的有效同步字,但找不到abc.mp3的同步字。

然而,将stringByAppendingPathComponent:@"song"替换为stringByAppendingPathComponent:@"song.mp3"对于abc.mp3是成功的,并且通常可以帮助其他mp3文件。

我们认为这个问题已经解决。如果您对此问题有任何疑问或关注,请直接更新您的报告(http://bugreport.apple.com)。

感谢您抽出时间通知我们这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接