IOS - 移动到单独的类(class)时播放 mp3 失败

标签 ios audio refactoring mp3

我在类里面成功地播放了一个 mp3 文件。但是,当我将功能移出到单独的类时,它失败了。

这是工作代码:

标题:

#import <AVFoundation/AVFoundation.h>

@interface QuestionController : UIViewController 
<UITableViewDataSource, UITableViewDelegate, UISplitViewControllerDelegate>
{
    AVAudioPlayer *audioPlayer;

}

工作代码:

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/A.mp3", [[NSBundle mainBundle] resourcePath]]];

    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;

    if (audioPlayer == nil)
        NSLog(@"audio errror: %@",[error description]);             
    else 
        [audioPlayer play];

这是新类(class):

标题:

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>


    @interface AudioPlayer : NSObject {

    }

    - (void *) playAudioFile:(NSString *) mp3File;

    @end

实现:

  #import "AudioPlayer.h"

    @implementation AudioPlayer

    - (void *) playAudioFile:(NSString *) mp3File {

        NSLog(@"mp3file to play: %@", mp3File ); 

        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@", mp3File, [[NSBundle mainBundle] resourcePath]]];

        NSError *error;

        AVAudioPlayer *audioPlayer;
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        audioPlayer.numberOfLoops = 0;

        if (audioPlayer == nil) {
            NSLog(@"audio errror: %@",[error description]);
        }
        else {
            [audioPlayer play];
        }
        [audioPlayer release];

        return 0; 
    }   

    @end

调用代码如下:

   AudioPlayer *audioPlayer = [[AudioPlayer alloc] init];

   [audioPlayer playAudioFile:@"/A.mp3"];

但是,当它在单独的类中运行时,它没有成功创建播放器并转到“audio player == nil”分支

这是输出:

012-07-21 07:14:54.480 MyQuiz[6655:207] mp3file to play: /A.mp3
2012-07-21 07:15:40.827 MyQuiz[6655:207] audio errror: Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)"

网址是“file://localhost/A.mp3”

知道我做错了什么吗?当我重构为单独的方法时,我总是遇到麻烦。真令人沮丧。

最佳答案

您的网址有误,请更改此行

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@", mp3File, [[NSBundle mainBundle] resourcePath]]];

为此:

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], mp3File]];

关于IOS - 移动到单独的类(class)时播放 mp3 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11591936/

相关文章:

ios - 我正在尝试在 Swift 中添加 MDCCard 以使用 Material Components 获取 Material Card View。错误 : No such module 'MaterialComponents.MaterialCards'

android - 具有我自己的音频PCM轨道的多路视频

c# - ASP.NET:重用相同的 Repeater ItemTemplate

c# - 有没有任何工具可以帮助我们将 IEnumerator 属性重构为 IList<T> 或类似的?

iphone - iTunesArtwork 突破发布提交到应用商店

ios - 在上传C#Xamarin之前调整图像大小

audio - 加密后测量音频文件.WAV的质量我的项目语言是VB.net

python - 不理解 Python 中主成分分析 (PCA) 的输出

.net - 避免 Web 服务神类

ios - glTexImage2D 读取超出缓冲区范围(iOS)